要求创建两个线程,实现文件打印到终端上,类似cat一个文件:
1.A线程读取文件中的内容
2.B线程将A线程中读取到的数据打印到终端上
3.当文件打印完毕后,结束进程。
程序:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <semaphore.h>
sem_t sem;
sem_t sem1;
char c=0;
int fd_r;
void *func(void *arg)
{
while(1)
{
ssize_t res;
/***********临界区********/
sem_wait(&sem);
res=read(fd_r,&c,1);
sem_post(&sem1);
if(res==0)
{
pthread_exit(NULL);
}
}
}
void *func1(void *arg)
{
while(1)
{
/***********临界区********/
sem_wait(&sem1);
printf("%c",c);
sem_post(&sem);
}
}
int main(int argc, const char *argv[])
{
//打开文件
fd_r=open("./pipe.c",O_RDONLY);
//创建2个信号量
sem_init(&sem,0,1);
sem_init(&sem1,0,0);
//创建2个线程
pthread_t tid;
pthread_t tid1;
if(pthread_create(&tid,NULL,func,NULL)!=0)
{
fprintf(stderr,"pthread_create failed");
return -1;
}
if(pthread_create(&tid1,NULL,func1,NULL)!=0)
{
fprintf(stderr,"pthread_create failed");
return -1;
}
pthread_detach(tid1);
pthread_join(tid,NULL);
//销毁信号量
sem_destroy(&sem);
sem_destroy(&sem1);
close(fd_r);
return 0;
}
运行效果: