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 }
12-14作业
最新推荐文章于 2024-08-20 19:00:09 发布