static std::mutex m;
void worker(int& result, std::condition_variable& cv, int set) {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
result = set;
cv.notify_all();
}
void consumer(std::condition_variable& cv, int idx) {
std::unique_lock<std::mutex> lock(m);
cv.wait(lock);
std::cout << "consumer #" << idx << " receive notification" << std::endl;
}
int main(int argc, char* argv[]) {
int cnt = 0;
std::condition_variable cv;
std::thread t1(worker, std::ref(cnt), std::ref(cv), 1);
std::thread t2(worker, std::ref(cnt), std::ref(cv), 2);
std::thread t3(consumer, std::ref(cv), 3);
std::thread t4(consumer, std::ref(cv), 4);
std::thread t5(consumer, std::ref(cv), 5);
std::thread t6(consumer, std::ref(cv), 6);
std::thread t7(consumer, std::ref(cv), 7);
std::thread t8(consumer, std::ref(cv), 8);
t1.detach();
t2.detach();
t3.detach();
t4.detach();
t5.detach();
t6.detach();
t7.detach();
t8.detach();
{
std::unique_lock<std::mutex> lock(m);
cv.wait(lock);
std::cout << cnt << std::endl;
}
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
return 0;
}