C++编程实现P操作原语、V操作原语
C++编程实现P操作原语、V操作原语C++编程实现P操作原语、V操作原语, 用所定义的PV操作解决下面的问题: 设学院某教室共有座位30个,任何时刻最多可容纳30名同学进入自习,当教室内人数少于30名时,则教室外等待的同学可立即进入,否则需在外面等待。把一个欲进入教室自习的同学看作一个进程。
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
int n = 30;
mutex m;
condition_variable cv;
void p() {
unique_lock<mutex> lk(m);
cv.wait(lk, [] { return n < 30; });
n++;
cout << "进程" << this_thread::get_id() << "进入教室" << endl;
lk.unlock();
}
void v() {
unique_lock<mutex> lk(m);
n--;
cout << "进程" << this_thread::get_id() << "离开教室" << endl;
cv.notify_one();
lk.unlock();
}
int main() {
for (int i = 0; i < 100; i++) {
thread t1(p);
thread t2(v);
t1.join();
t2.join();
}
return 0;
}编者按:看到评论说代码不能运行,现在截图GIF图片,即编者编译代码并运行的录相截图。
页:
[1]