在linux环境下,巧妙运用信号量解决水果放取问题,这是一个有趣且实用的多线程同步问题。以下是该问题的思维导图、代码演示和思路解析。

一. 信号量相关实验回顾
回顾:使用信号量实现线程互斥
解析:利用信号量实现两个线程互斥输出1-10数字。传送门
回顾:巧妙运用信号量控制两个线程之间谁先执行
传送门
回顾:巧妙运用信号量实现线程间通信
传送门
二. 巧妙运用信号量解决水果放取问题(思维导图&代码演示&思路解析)
问题描述:一个盘子只能放一个水果,爸爸往里面放苹果,妈妈往里面放橘子,儿子专门等吃橘子,女儿专门等吃苹果。只要盘子空,爸爸或妈妈就可以往里面放水果;仅当盘子里有自己需要的水果时,儿子或女儿才可以取出吃。
设置三个信号量:
网易人工智能
网易数帆多媒体智能生产力平台
195 查看详情
plate:初始值为1,优先执行,面向父母端。appleReady:初始值为0,对应女儿等待苹果。orangeReady:初始值为0,对应儿子等待橘子。
定义:
fruitOnPlate:表示盘子中是否有水果。fruitType:表示盘子中水果的类型。https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15bdefine APPLE 1 和 https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15bdefine ORANGE 2:表示水果类型。
信号量操作:
信号量等待(P操作):sem_wait()信号量唤醒(V操作):sem_post()

代码语言:C
运行次数:0
https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15binclude https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15binclude https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15binclude https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15binclude https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15binclude https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15bdefine APPLE 1https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15bdefine ORANGE 2// 表示放入水果int fruitOnPlate = 0;int fruitType = 0;// 设置信号量sem_t plate, appleReady, orangeReady;void *father(void *arg) { while (1) { sem_wait(&plate); fruitOnPlate = 1; fruitType = APPLE; // 放入苹果 printf("Father put an apple.n"); sem_post(&appleReady); sleep(rand() % 10); // 睡眠随机时间 }}void *mother(void *arg) { while (1) { sem_wait(&plate); fruitOnPlate = 1; fruitType = ORANGE; // 放入橘子 printf("Mother put an orange.n"); sem_post(&orangeReady); sleep(rand() % 10); // 睡眠随机时间 }}void *son(void *arg) { while (1) { sem_wait(&orangeReady); // 等待橘子 if (fruitType == ORANGE) { printf("Son ate an orange.n"); sem_post(&plate); } }}void *daughter(void *arg) { while (1) { sem_wait(&appleReady); // 等待苹果 if (fruitType == APPLE) { printf("Daughter ate an apple.n"); sem_post(&plate); } }}int main() { pthread_t f_thread, m_thread, son_thread, dau_thread; sem_init(&plate, 0, 1); sem_init(&appleReady, 0, 0); sem_init(&orangeReady, 0, 0); pthread_create(&f_thread, NULL, father, NULL); pthread_create(&m_thread, NULL, mother, NULL); pthread_create(&son_thread, NULL, son, NULL); pthread_create(&dau_thread, NULL, daughter, NULL); pthread_join(f_thread, NULL); pthread_join(m_thread, NULL); pthread_join(son_thread, NULL); pthread_join(dau_thread, NULL); sem_destroy(&plate); sem_destroy(&appleReady); sem_destroy(&orangeReady); return 0;}
通过以上代码,我们可以看到信号量的巧妙运用,确保了水果放取的正确性和同步性。
以上就是【Linux】巧妙运用<信号量>解决<水果放取问题>(思维导图&代码演示&思路解析)的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/820951.html
微信扫一扫
支付宝扫一扫