12-14作业

1 #include <stdio.h>
  2 #include <unistd.h>
  3 #include <pthread.h>
  4 #include <stdlib.h>
  5 #include <sys/types.h>
  6 #include <sys/stat.h>
  7 #include <fcntl.h>
  8 #include <semaphore.h>
  9 #include <string.h>
 10 
 11 typedef struct info
 12 {
 13     int fd_r;
 14 //  int fd_w;
 15     off_t size;
 16     sem_t sem1;
 17     sem_t sem2;
 18 }info;
 19 
 20 char c=0;
 21 
 22 ssize_t res=0;
 23 
 24 void* funa(void*a)
 25 {
 26     int fd_r=((info*)a)->fd_r;
 27 //  int fd_w=((info*)a)->fd_w;
 28     off_t size=((info*)a)->size;
 29     sem_t sem1=((info*)a)->sem1;
 30     sem_t sem2=((info*)a)->sem2;
 31 
 32     while(1)
 33     {
 34         sem_wait(&sem1);
 35     //  bzero(s,sizeof(s));
 36         res= read(fd_r,&c,1);
 37         if(res==0)
 38             break;
 39         sem_post(&sem2);                                                       
 40     }
 41 
 42 }
 43 
 44 void* funb(void*a)
{
 46 
 47     int fd_r=((info*)a)->fd_r;
 48 //  int fd_w=((info*)a)->fd_w;
 49     off_t size=((info*)a)->size;
 50     sem_t sem1=((info*)a)->sem1;                                               
 51     sem_t sem2=((info*)a)->sem2;
 52 
 53     while(1)
 54     {
 55         sem_wait(&sem2);
 56         printf("%c",c);
 57         fflush(stdout);
 58         sem_post(&sem1);
 59     }
 60 }
 61 
 62 int main(int argc, const char *argv[])
 63 {
 64     pthread_t tid1;
 65     pthread_t tid2;
 66 
 67     int fd_r=open("main.c",O_RDONLY);
 68 //  int fd_w=open("main.c",O_WRONLY);
 69 
 70     off_t size=lseek(fd_r,0,SEEK_END);
 71     lseek(fd_r,0,SEEK_SET);
 72 
 73     sem_t sem1;
 74     sem_t sem2;
 75 
 76     sem_init(&sem1,0,1);
 77     sem_init(&sem2,0,1);
 78     sem_wait(&sem2);
 79 
 80     info msg;
 81     msg.fd_r=fd_r;
 82 //  msg.fd_w=fd_w;
 83     msg.size=size;
 84     msg.sem1=sem1;
 85     msg.sem2=sem2;
  pthread_create(&tid1,NULL,funa,&msg);
 88     pthread_create(&tid2,NULL,funb,&msg);
 89 
 90     pthread_join(tid1,NULL);
 91     pthread_join(tid2,NULL);
 92 
 93     sem_destroy(&sem1);
 94     sem_destroy(&sem2);
 95 
 96     close(fd_r);
 97 //  close(fd_w);                                                               
 98 
 99 }

                                                                          

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值