具体参照王道考研操作系统77页
实现代码,环境c++11及以上
#include <iostream>
#include <thread>
using namespace std;
/*实现两个线程竞争时互斥*/
int flag[2], trun;
void pr(char ch, int i) {
flag[i] = 1;
trun = i ^ 1;
while (flag[i ^ 1] && trun == (i ^ 1))
;
cout << ch << " pr......" << endl;
flag[i] = 0;
}
int main() {
thread thread1(pr, 'A', 0);
thread thread2(pr, 'B', 1);
thread1.join();
thread2.join();
return 0;
}