#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<semaphore.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
pthread_mutex_t pth;
pthread_cond_t nd;
sem_t sem_1;
sem_t sem_2;
char c=0;
//分线程pth_1
void* fun1(void *gre)
{
int cont=0;
pid_t pd=*(pid_t*)gre;
while(1)
{
//申请信号量 p
if(sem_wait(&sem_1)<0)
{
printf("__%d__\n",__LINE__);
perror("sem_wait");
pthread_exit(NULL);
}
cont=read(pd,&c,sizeof(char));
if(cont==0)
{
pthread_exit(NULL);
}
//释放信号量 p
if(sem_post(&sem_2)<0)
{
printf("__%d__\n",__LINE__);
perror("sem_wait");
pthread_exit(NULL);
}
}
}
//分线程pth_2
void* fun2(void *gre)
{
int cont=0;
pid_t pd=*(pid_t*)gre;
while(1)
{
//申请信号量 p
if(sem_wait(&sem_2)<0)
{
printf("__%d__\n",__LINE__);
perror("sem_wait");
pthread_exit(NULL);
}
cont=write(1,&c,1);
if(cont==0)
{
pthread_exit(NULL);
}
//释放信号量 p
if(sem_post(&sem_1)<0)
{
printf("__%d__\n",__LINE__);
perror("sem_post");
break;
}
}
}
int main(int argc, const char *argv[])
{
//以读的方式打开一个文件
pid_t pd=open("./pthread_cond.c",O_RDONLY);
if(pd<0)
{
printf("__%d__\n",__LINE__);
perror("open");
return -1;
}
//创建一个信号灯
if(sem_init(&sem_1,0,1))
{
printf("__%d__\n",__LINE__);
perror("sem_init");
return -1;
}
//创建一个信号灯
if(sem_init(&sem_2,0,0))
{
printf("__%d__\n",__LINE__);
perror("sem_init");
return -1;
}
//创建两个分线程
pthread_t pth_1=0;
if(pthread_create(&pth_1,NULL,fun1,&pd))
{
fprintf(stderr,"创建失败\n");
return -1;
}
pthread_t pth_2=0;
if(pthread_create(&pth_2,NULL,fun2,&pd))
{
fprintf(stderr,"创建失败\n");
return -1;
}
//阻塞等待分线程pth_1退出、
pthread_join(pth_1,NULL);
pthread_join(pth_2,NULL);
return 0;
}
要求创建两个线程,实现文件打印到终端上,类似cat一个文件:A线程读取文件中的内容B线程将A线程中读取到的数据打印到终端上当文件打印完毕后,结束进程。
最新推荐文章于 2024-07-22 10:02:43 发布