#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
#include <unistd.h>
#include <fcntl.h>
//存储互斥锁的变量 初始化方式2;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//条件变量
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
int flag = 0;
int i=0,j=0,k=0;
char a='A',b='B',c='C';
void *callBacka(void* arg)
{
while(i<10)
{
pthread_mutex_lock(&mutex);
if(flag != 0)
{
pthread_cond_wait(&cond, &mutex);
}
printf("%c",a);
i++;
flag = 1;
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void *callBackb(void* arg)
{
while(j<10)
{
pthread_mutex_lock(&mutex);
if(flag != 1)
{
pthread_cond_wait(&cond1, &mutex);
}
printf("%c",b);
j++;
flag=2;
pthread_cond_signal(&cond2);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void *callBackc(void* arg)
{
while(k<10)
{
pthread_mutex_lock(&mutex);
if(flag != 2)
{
pthread_cond_wait(&cond2, &mutex);
}
printf("%c",c);
k++;
flag=0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//创建三个分支线程
pthread_t tid1,tid2,tid3;
if(pthread_create(&tid1,NULL,callBacka,NULL)!=0)
{
perror("pthread_create");
return -1;
}
if(pthread_create(&tid2,NULL,callBackb,NULL)!=0)
{
perror("pthread_create");
return -1;
}
if(pthread_create(&tid3,NULL,callBackc,NULL)!=0)
{
perror("pthread_create");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
//销毁互斥锁
pthread_mutex_destroy(&mutex);
//销毁条件变量
pthread_cond_destroy(&cond);
puts("");
return 0;
}
08-02
1073