1. 用条件变量的方式实现:现有ID号为a b c的三个线程,每个线程的任务都是循环打印自己id号,要求打印的顺序为abc
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond,cond1,cond2= PTHREAD_COND_INITIALIZER;
int flag=0;
void* callback(void *arg)
{
while(1)
{
///临界代码///
pthread_mutex_lock(&mutex);
if(flag!=0)
{
pthread_cond_wait(&cond,&mutex);
}
printf("a\n");
flag = 1;
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&mutex);
///临界代码///
}
}
void* callback1(void *arg)
{
while(1)
{
///临界代码///
pthread_mutex_lock(&mutex);
if(flag!=1)
{
pthread_cond_wait(&cond1,&mutex);
}
printf("b\n");
flag=2;
pthread_cond_signal(&cond2);
pthread_mutex_unlock(&mutex);
///临界代码///
}
}
void* callback2(void *arg)
{
while(1)
{
///临界代码///
pthread_mutex_lock(&mutex);
if(flag!=2)
{
pthread_cond_wait(&cond2,&mutex);
}
printf("c\n");
flag = 0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
///临界代码///
}
}
int main(int argc, const char *argv[])
{
pthread_t tid,tid1,tid2;
if(pthread_create(&tid,NULL,callback,NULL)!=0)
{
printf("error\n");
return -1;
}
if(pthread_create(&tid1,NULL,callback1,NULL)!=0)
{
printf("error1\n");
return -1;
}
if(pthread_create(&tid2,NULL,callback2,NULL)!=0)
{
printf("error\n");
return -1;
}
pthread_join(tid1,NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
2.创建两个线程,实现将一个文件的内容打印到终端上,类似cat一个文件
一个线程读取文件中的内容
另一个线程将读取到的内容打印到终端上。
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
sem_t sem1,sem2;
int fd_r;
char c;
int res=0;
void *callback(void *arg)
{
while(1)
{
sem_wait(&sem1);
res=read(fd_r,&c,1);
if(res<=0)
break;
sem_post(&sem2);
}
pthread_exit(NULL);
}
void *callback1(void *arg)
{
while(1)
{
sem_wait(&sem2);
if(res<=0)
break;
printf("%c",c);
sem_post(&sem1);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
sem_init(&sem1,0,1);
sem_init(&sem2,0,0);
fd_r=open("./test.c",O_RDONLY);
pthread_t tid,tid1;
if(pthread_create(&tid,NULL,callback,NULL)!=0)
{
printf("tid error\n");
return -1;
}
if(pthread_create(&tid1,NULL,callback1,NULL)!=0)
{
printf("tid1 error\n");
return -1;
}
pthread_join(tid,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
close(fd_r);
return 0;
}