寿司店问题 PV操作 pthread表示

寿司店问题。假设一个寿司店有 5 个座位,如果你到达的时候有一个空座位,你可以立刻就坐。但是如果你到达的时候 5 个座位都是满的有人已经就坐,这就意味着这些人都是一起来吃饭的,那么你需要等待所有的人一起离开才能就坐。编写同步原语,实现这个场景的约束。


 1 #include <stdio.h>
 2 #include <unistd.h> 
 3 #include <pthread.h>
 4 #include <semaphore.h>
 5 sem_t mutex;
 6 sem_t allowin;
 7 int waiting = 0;
 8 int eating = 0; 
 9 int barrier = 0;  
10 void *thread_a(void *in)
11 {
12     sem_wait(&mutex); 
13     if (barrier) { 
14         waiting++; 
15         sem_post(&mutex);
16         sem_wait(&allowin); 
17     }     
18     else {
19         eating++; 
20         barrier = (eating == 5); 
21         sem_post(&mutex);  
22         
23     }
24     
25     printf("No.%s takes seat and eats (person eating:%d)\n ", (char *)in, eating);
26     sleep(1); 
27     sem_wait(&mutex);      
28     eating--; 
29     if (eating == 0) {
30         int n = (5 < waiting) ? 5 : waiting; 
31         waiting -= n; 
32         eating += n; 
33         barrier = (eating == 5); 
34         for (int i = 0; i < n; i++)
35         sem_post(&allowin); 
36     }
37     sem_post(&mutex); 
38     printf("No.%s leaves\n", (char *)in);
39     pthread_exit((void *)0);
40 }
41 int main()
42 {
43     const int maxn = 10; 
44     pthread_t a[maxn];  /* thread id a, b, c*/
45     char *strs[] = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"}; 
46     int val;         /* used for function return result */
47     /* init sem1 sem2 to 0 , any thread waits for it will be blocked*/
48     sem_init(&mutex, 0, 1);
49     sem_init(&allowin, 0, 1);
50     for (int i = 0; i < maxn; i++)
51     pthread_create(&a[i], NULL, thread_a, (void *)strs[i]);
52     for (int i = 0; i < maxn; i++)
53     pthread_join(a[i], (void **)0);
54     sem_destroy(&mutex);
55     sem_destroy(&allowin);
56  
57     printf("Main thread is over\n");
58     return 0;
59 }

 

posted @ 2022-05-09 14:20  cywuuuu  阅读(102)  评论(0编辑  收藏  举报