吃水果问题,c++版

这是一个使用C++编写的程序,模拟了父亲、母亲、儿子和女儿四个进程对苹果和橘子的操作。父亲和母亲随机放苹果或橘子,儿子吃橘子,女儿吃苹果。程序中使用了信号量来处理进程间的同步问题,确保资源的有效共享。运行过程中,会显示各进程的状态,防止出现死锁情况。
摘要由CSDN通过智能技术生成

#include <iostream>

#include <signal.h>

#include <ctime>

#include <cstdlib>

#include <windows.h>

using namespacestd;

 

 

int apple=0;

int orange=0;

bool father_lag;

bool mother_lag;

bool son_lag;

bool daugther_lag;

 

void father()

{

                   apple++;

                   cout<<"father 放了一个苹果,";

}

 

void mother()

{

                   orange++;

                   cout<<"mother

  • 4
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用C++实现的爸爸放苹果、妈妈放橘子、儿子吃橘子、女儿吃苹果问题的P/V经典操作: ```c++ #include <iostream> #include <thread> #include <mutex> #include <condition_variable> using namespace std; mutex mtx; condition_variable cv; int apple = 0, orange = 0; void father() { for (int i = 0; i < 5; ++i) { unique_lock<mutex> lck(mtx); while (apple + 1 > 3) { // 苹果数超过3个就等待 cv.wait(lck); } ++apple; // 放苹果 cout << "Father put an apple." << endl; cv.notify_all(); // 通知其他线程有新水果放入 } } void mother() { for (int i = 0; i < 5; ++i) { unique_lock<mutex> lck(mtx); while (orange + 1 > 3) { // 橘子数超过3个就等待 cv.wait(lck); } ++orange; // 放橘子 cout << "Mother put an orange." << endl; cv.notify_all(); // 通知其他线程有新水果放入 } } void son_eat_orange() { for (int i = 0; i < 5; ++i) { unique_lock<mutex> lck(mtx); while (orange < 1) { // 没有橘子就等待 cv.wait(lck); } --orange; // 吃一个橘子 cout << "Son ate an orange." << endl; cv.notify_all(); // 通知其他线程有水果被取走 } } void daughter_eat_apple() { for (int i = 0; i < 5; ++i) { unique_lock<mutex> lck(mtx); while (apple < 1) { // 没有苹果就等待 cv.wait(lck); } --apple; // 吃一个苹果 cout << "Daughter ate an apple." << endl; cv.notify_all(); // 通知其他线程有水果被取走 } } int main() { thread father_thread(father); thread mother_thread(mother); thread son_thread(son_eat_orange); thread daughter_thread(daughter_eat_apple); father_thread.join(); mother_thread.join(); son_thread.join(); daughter_thread.join(); return 0; } ``` 在上述代码中,我们使用了互斥锁和条件变量来实现线程间的同步。其中,`father()`和`mother()`函数分别代表父亲和母亲放水果的线程,`son_eat_orange()`和`daughter_eat_apple()`函数分别代表儿子和女儿吃水果的线程。在`father()`和`mother()`函数中,每次放水果之前都会检查当前水果数量是否已经超过3个,如果超过了就等待其他线程取走一些水果后再放入新的水果;在`son_eat_orange()`和`daughter_eat_apple()`函数中,每次吃水果之前都会检查当前是否还有水果可吃,如果没有就等待其他线程放入新的水果。每次有水果被放入或被取走时,都会通过条件变量通知其他线程。最后,我们启动了4个线程,并使用`join()`函数等待所有线程执行完毕后退出程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值