#include <bits/stdc++.h>
#include <thread>
#include <mutex>
using namespace std;
mutex g_mu;
condition_variable cond;
int g_val;
const int N = 4; //指定打印的字母个数,A为1,AB为2,ABC为3
const int MAXTIME = 100; //打印次数
class printC
{
public:
printC(char _c, int _ct = 0) : c(_c), cur_time(_ct)
{
}
void operator()() //重载(),使得对象变成仿函数
{
while (true)
{
if (cur_time < MAXTIME)
{
unique_lock<mutex> guard(g_mu); //加锁,进入临界区
cond.wait(guard, [this] //引用this指针
{
if(this->c -'A' == g_val &&
this->cur_time < MAXTIME)
return true;
else
return false; }); //等待条件满足
cout << c;
g_val = (g_val + 1) % N;
++cur_time;
// guard.unlock();
cond.notify_all();
}
else
{
return;
}
}
}
private:
char c;
int cur_time = 0;
};
void test()
{
vector<thread> ts;
for (int i = 0; i < N; ++i)
{
printC tmp(i + 'A');
ts.push_back(move(thread(move(tmp)))); //move函数进行资源转移,提高效率
}
for (int i = 0; i < N; ++i)
{
ts[i].join();
}
}
int main()
{
test();
return 0;
}
注意bits/stdc++.h头文件只能在g++编译器下使用,Windows自带的编译器需要手动添加这个头文件。或者将#include<bits/stdc++.h>替换成下面的头文件引入:
#include<iostream>
#include<vector>
|