代码如下:
#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
//创建结构体
struct stu
{
sem_t *sem1;
sem_t *sem2;
int fd_r;
};
char a = 0;
ssize_t res = 0;
void *pthread_r(void *p) //完成读文件
{
int fd_r = ((struct stu *)p)->fd_r;
sem_t *sem1 = ((struct stu *)p)->sem1;
sem_t *sem2 = ((struct stu *)p)->sem2;
//printf("sem1=%p\n",sem1);
//printf("sem2=%p\n",sem2);
while(1)
{
//sleep(3);
sem_wait(sem1);
//printf("开始读文件\n");
if((res = read(fd_r,&a,1))<0)
{
perror("read");
return NULL;
}
sem_post(sem2);
if(0 == res)
{
break;
}
//printf("res = %ld\n",res);
}
//printf("读文件完成\n");
return NULL;
}
void *pthread_w(void *p) //完成输出
{
int fd_r = ((struct stu *)p)->fd_r;
sem_t *sem1 = ((struct stu *)p)->sem1;
sem_t *sem2 = ((struct stu *)p)->sem2;
//printf("sem1=%p\n",sem1);
//printf("sem2=%p\n",sem2);
while(1)
{
//sleep(3);
//printf("宪政2\n");
sem_wait(sem2);
//printf("输出字符\n");
fprintf(stderr,"%c",a);
sem_post(sem1);
if(0 == res)
{
break;
}
}
//printf("输出文件完成\n");
return NULL;
}
int main(int argc, const char *argv[])
{
pthread_t pth_r;
pthread_t pth_w;
sem_t sem1;
sem_t sem2;
int fd_r;
struct stu A;
//打开文件
if((fd_r = open("./1.txt",O_RDONLY))<0)
{
perror("open");
return -1;
}
//printf("fd_r= %d\n",fd_r);
//申请信号量(信号灯)
if(sem_init(&sem1,0,1)<0)
{
perror("sem_init");
return -1;
}
if(sem_init(&sem2,0,0)<0)
{
perror("sem_init");
return -1;
}
//printf("sem1=%p\n",&sem1);
//printf("sem2=%p\n",&sem2);
A.sem1 = &sem1;
A.sem2 = &sem2;
A.fd_r = fd_r;
//printf("sem1=%p\n",A.sem1);
//printf("sem2=%p\n",A.sem2);
//创建分支线程
if(pthread_create(&pth_r,NULL,pthread_r,&A) != 0)
{
perror("pthread_create");
return -1;
}
if(pthread_create(&pth_w,NULL,pthread_w,&A) != 0)
{
perror("pthread_create");
return -1;
}
//printf("准备关闭程序\n");
//阻塞线程
pthread_join(pth_r,NULL);
pthread_join(pth_w,NULL);
//销毁信号量
sem_destroy(&sem1);
sem_destroy(&sem2);
//关闭文件
close(fd_r);
return 0;
}
终端执行结果:
ubuntu@ubuntu:IO$ gcc 3homework.c -pthread
ubuntu@ubuntu:IO$ ./a.out
hello huawei
hello zhongxing
hello DJI
hello kedaxuefei