六、三線程讀寫緩衝區
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <pthread.h>
5 #include<string.h>
6 char buf[50];
7 void *twrite(char *arg)
8 {
9 strcpy(buf+strlen(buf),arg);
10 printf("write success\n");
11 }
12 void *tread()
13 {
14 printf("read:%s\n",buf);
15 }
16 int main()
17 {
18 pthread_t id1,id2,id3;
19 char *s1="I am write1\n";
20 char *s2="I am write2\n";
21 pthread_create(&id1,NULL,twrite,s1);
22 pthread_join(id1,NULL);
23 pthread_create(&id2,NULL,twrite,s2);
24 pthread_join(id2,NULL);
25 pthread_create(&id3,NULL,tread,NULL);
26 pthread_join(id3,NULL);
27 printf("I am main\n");
28 return 0;
29 }
執行結果:
write success
write success
read:I am write1
I am write2
I am main
七、三線程讀寫有名管道
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 #include <pthread.h> 5 #include<string.h> 6 #include<fcntl.h> 7 #include<sys/stat.h> 8 #include<sys/types.h> 9 #define FIFO "myfifo" 10 void *twrite(char *arg) 11 { 12 int fd; 13 umask(0); 14 fd=open(FIFO,O_WRONLY|O_NONBLOCK); 15 write(fd,arg,strlen(arg)+1); 16 printf("write success\n"); 17 } 18 void *tread() 19 { 20 int fd; 21 char buf[1024]; 22 umask(0); 23 fd=open(FIFO,O_RDONLY|O_NONBLOCK); 24 read(fd,buf,1024); 25 printf("read:%s\n",buf); 26 } 27 int main() 28 { 29 pthread_t id1,id2,id3; 30 char *s1="I am write1\n"; 31 char *s2="I am write2\n"; 32 mkfifo(FIFO,O_CREAT|O_EXCL|0777); 33 pthread_create(&id3,NULL,tread,NULL); 34 pthread_join(id3,NULL); 35 pthread_create(&id1,NULL,twrite,s1); 36 pthread_join(id1,NULL); 37 pthread_create(&id3,NULL,tread,NULL); 38 pthread_join(id3,NULL); 39 pthread_create(&id2,NULL,twrite,s2); 40 pthread_join(id2,NULL); 41 pthread_create(&id3,NULL,tread,NULL); 42 pthread_join(id3,NULL); 43 return 0; 44 }
執行結果:
read:
write success
read:I am write1
write success
read:I am write2
問題:
如果註釋掉33、34。第一次讀出的是亂碼???