C++实现P/V经典操作爸爸放苹果妈妈放橘子儿子吃橘子女儿吃苹果问题代码
时间: 2023-06-26 16:10:36 浏览: 96
下面是使用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()`函数等待所有线程执行完毕后退出程序。