三个线程有序循环输出ABC
#include <bits/stdc++.h>
#include <thread>
#include <condition_variable>
using namespace std;
mutex mtx;
condition_variable cvar;
int g_ch = 0;
void print_fun(char ch) {
int cid = ch-'A';
for (int i = 0; i < 5; i++) {
unique_lock<mutex> ulk(mtx);
cvar.wait(ulk, [cid] {
return cid == g_ch;
});
cout << (char)(cid + 'A') <<endl;
g_ch = (cid + 1) % 3;
ulk.unlock();
cvar.notify_all();
}
}
int main() {
vector<thread> threads;
threads.push_back(thread(print_fun, 'A'));
threads.push_back(thread(print_fun, 'B'));
threads.push_back(thread(print_fun, 'C'));
for_each(threads.begin(), threads.end(), mem_fn(&thread::join));
return 0;
}
|