标签:操作 div class init void his 吃水果 main join()
Linux下的semaphore.h库提供信号量sem_t 结构体类型。sem_t 的三个常用操作:
举例子:
吃水果问题演示信号量的使用。桌上放了一个空盘子,能容纳三个水果。父亲以
1/3 的概率往盘子里放苹果,2/3 的概率放橘子。两个儿子竞争拿走苹果,一个女儿专门拿 走橘子。信号量的使用请参见课堂笔记。下面是模拟程序的代码:
1 #include<cstdio> 2 #include<chrono> 3 #include<cstdlib> 4 #include<thread> 5 #include<semaphore.h> 6 using namespace std; 7 sem_t empty,apple,orange; //定义三个信号量 8 void son(int id){ 9 while(true){ 10 sem_wait(&apple); 11 printf("Son %d takes an apple",id); 12 sem_post(&empty); 13 } 14 } 15 void daughter(){ 16 while(true){ 17 sem_wait(&orange); 18 printf("Daughter takes an orange\n"); 19 sem_post("&empty"); 20 } 21 } 22 void father(){ 23 while(true){ 24 int fruit=rand()%3; 25 sem_wait(&empty); 26 if(fruit==0){ 27 printf("father puts an apple \n"); 28 sem_post(&apple); 29 }else{ 30 printf("father puts an orange\n"); 31 sem_post("&orange"); 32 } 33 this_thread::sleep_for(chrono::seconds(1)); 34 } 35 } 36 int main(){ 37 sem_init(&empty,0,3); 38 sem_init(&apple,0,0); 39 sem_init(&orange,0,0); 40 thread f(father); 41 thread s1(son,1); 42 thread s2(son,2); 43 thread d(daughter); 44 f.join(); 45 s1.join(); 46 s2.join(); 47 d.join(); 48 return 0; 49 }
标签:操作 div class init void his 吃水果 main join()
原文地址:https://www.cnblogs.com/technicist/p/12728476.html