loopoutput str buf[]="1234567" in original direction and reversed direction;
use func semaphore;
flag has been banned;
1 #include <stdio.h>
2 #include <myhead.h>
3 #include <string.h>
4 char buf[]="1234567";
5 sem_t sem1,sem2;
6 void* callback1(void* arg)
7 {
8 while(1)
9 {
10 sem_wait(&sem1);
11 printf("%s\n",buf);
12 sem_post(&sem2);
13 // sleep(2);
14 }
15 pthread_exit(NULL);
16 }
17 void* callback2(void* arg)
18 {
19 int i=0,j=0;
20 char c;
21 while(1)
22 {
23 sem_wait(&sem2);
24 for(i=0,j=strlen(buf)-1;i<j;i++,j--)
25 {
26 c=buf[i];
27 buf[i]=buf[j];
28 buf[j]=c;
29 // sleep(1);
30 }
31 sem_post(&sem1);
32 }
33 pthread_exit(NULL);
34 }
35 int main(int argc, const char *argv[])
36 {
37 //creat a lock
38 // pthread_mutex_t mutex;
39 //pthread_mutex_init(&mutex,NULL);
40 if(sem_init(&sem1,0,1)<0)
41 {
42 perror("sem_init");
43 return -1;
44 }
45 if(sem_init(&sem2,0,0)<0)
46 {
47 perror("sem_init");
48 return -1;
49 }
50 pthread_t tid1,tid2;
51 if(pthread_create(&tid1,NULL,callback1,NULL)!=0)
52 {
53 printf("pthread_creat");
54 return -1;
55 }
56 if(pthread_create(&tid2,NULL,callback2,NULL)!=0)
57 {
58 printf("pthread_creat");
59 return -1;
60 }
61 pthread_detach(tid2); //you can use only one between join and detach
62 pthread_join(tid1,NULL);
63 //destory the lock
64 //pthread_mutex_destory(&mutex);
65 sem_destroy(&sem1);
66 sem_destroy(&sem2);
67
68 return 0;
69 }