利用线程同步互斥机制实现
利用条件变量实现ABC循环输出十次
main函数
#include<stdio.h>
#include<pthread.h>
pthread_cond_t cond1; //创建3个条件变量
pthread_cond_t cond2;
pthread_cond_t cond3;
pthread_mutex_t mutex;
int flog=0;
void* A(void* arg) //线程A输出A
{
int i=0;
while(i<10)
{
pthread_mutex_lock(&mutex);
if(0 != flog)
{
pthread_cond_wait(&cond1,&mutex); //满足条件等到条件变量cond1唤醒
}
printf("A");
i++;
flog=1;
pthread_cond_signal(&cond2); //信号唤醒条件变量为cond2的线程内容,也就是B线程
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void* B(void* arg) //线程B输出B
{
int i=0;
while(i<10)
{
pthread_mutex_lock(&mutex);
if(1 != flog)
{
pthread_cond_wait(&cond2,&mutex); //满足条件等到条件变量cond2唤醒
}
printf("B");
i++;
flog=2;
pthread_cond_signal(&cond3); //信号唤醒条件变量为cond3的线程内容,也就是C线程
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void* C(void* arg) //线程C输出C
{
int i=0;
while(i<10)
{
pthread_mutex_lock(&mutex);
if(2 != flog)
{
pthread_cond_wait(&cond3,&mutex); //满足条件等到条件变量cond3唤醒
}
printf("C\n");
i++;
flog=0;
pthread_cond_signal(&cond1); //信号唤醒条件变量为cond1的线程内容,也就是A线程
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main()
{
if(pthread_mutex_init(&mutex,NULL)!=0)
{
perror("pthread_mutex_init");
return -1;
}
if(pthread_cond_init(&cond1,NULL)!=0)
{
perror("pthread_cond_init");
return -1;
}
if(pthread_cond_init(&cond2,NULL)!=0)
{
perror("pthread_cond_init");
return -1;
}
if(pthread_cond_init(&cond3,NULL)!=0)
{
perror("pthread_cond_init");
return -1;
}
pthread_t tid1,tid2,tid3;
if(pthread_create(&tid1,NULL,A,NULL)!=0)
{
perror("pthread_create");
return -1;
}
if(pthread_create(&tid2,NULL,B,NULL)!=0)
{
perror("pthread_create");
return -1;
}
if(pthread_create(&tid3,NULL,C,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(&cond1);
pthread_cond_destroy(&cond2);
pthread_cond_destroy(&cond3);
return 0;
}
实现结果
利用信号量实现打印文件内容到终端
main函数
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
#include<fcntl.h>
int fq;
char b;
int res;
sem_t sem1,sem2;
void* xc1(void* arg) //线程1从文件中取内容
{
char a;
while(1)
{
sem_wait(&sem1);
res=read(fq,&a,1);
b=a;
if(res==0)
{
sem_post(&sem2);
break;
}
sem_post(&sem2);
}
pthread_exit(NULL);
}
void* xc2(void* arg) //线程2从文件中取内容
{
while(1)
{
sem_wait(&sem2);
if(res==0)
{
break;
}
printf("%c",b);
sem_post(&sem1);
}
pthread_exit(NULL);
}
int main()
{
int fp=open("./1.c",O_RDONLY);
fq=fp;
if(sem_init(&sem1,0,1)<0)
{
perror("sem_init");
return -1;
}
if(sem_init(&sem2,0,0)<0)
{
perror("sem_init");
return -1;
}
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,xc1,NULL)!=0)
{
perror("pthread_create");
return -1;
}
if(pthread_create(&tid2,NULL,xc2,NULL)!=0)
{
perror("pthread_create");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
return 0;
}
实现结果