pratice0416:func semaphore using

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 }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值