1.拷贝文件
2.信号量
#include "head.h"
sem_t sem1,sem2;
void* inter_a(void* arg)
{
while(1)
{
sleep(1);
printf("A\n");
sem_post(&sem1);
}
pthread_exit(NULL);
}
void* inter_b(void* arg)
{
while(1)
{
sem_wait(&sem1);
printf("B\n");
sem_post(&sem2);
}
pthread_exit(NULL);
}
void* inter_c(void* arg)
{
while(1)
{
sem_wait(&sem2);
printf("C\n");
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
sem_init(&sem1,0,0);
sem_init(&sem2,0,0);
pthread_t tid1,tid2,tid3;
if((errno=pthread_create(&tid1,NULL,inter_a,NULL))!=0)
PRINT_ERROR("create error");
if((errno=pthread_create(&tid2,NULL,inter_b,NULL))!=0)
PRINT_ERROR("create error");
if((errno=pthread_create(&tid3,NULL,inter_c,NULL))!=0)
PRINT_ERROR("create error");
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
return 0;
}
条件变量
#include "head.h"
pthread_cond_t cond;
pthread_cond_t cond2;
pthread_cond_t cond3;
//pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex;
int flag=0;
void* inter_a(void* arg)
{ while(1)
{
pthread_mutex_lock(&mutex);
if(flag==1)
pthread_cond_wait(&cond,&mutex);
flag=1;
printf("A\n");
pthread_cond_signal(&cond2);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void* inter_b(void* arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(flag==0)
pthread_cond_wait(&cond2,&mutex);
//唤醒后又上了一次锁,所以后面要再一次解锁
flag=0;
printf("B\n");
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond3);
}
pthread_exit(NULL);
}
void* inter_c(void* arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(flag==2)
pthread_cond_wait(&cond3,&mutex);
//唤醒后又上了一次锁,所以后面要再一次解锁
flag=2;
printf("C\n");
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_cond_init(&cond,NULL);
pthread_cond_init(&cond2,NULL);
pthread_cond_init(&cond3,NULL);
pthread_t rid,rid2,rid3;
if((errno=pthread_create(&rid,NULL,inter_a,NULL)!=0))
PRINT_ERROR("create error");
if((errno=pthread_create(&rid2,NULL,inter_b,NULL)!=0))
PRINT_ERROR("create error");
if((errno=pthread_create(&rid3,NULL,inter_c,NULL)!=0))
PRINT_ERROR("create error");
pthread_join(rid,NULL);
pthread_join(rid2,NULL);
pthread_join(rid3,NULL);
pthread_cond_destroy(&cond);
pthread_cond_destroy(&cond2);
pthread_cond_destroy(&cond3);
return 0;
}