...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
std::mutex mutex;
std::condition_variable cond;
void run_step(size_t my_step) {
static size_t current_step = 0;
std::unique_lock<std::mutex> lk(mutex);
std::cout << "Thread " << my_step << " has the lock" << std::endl;
while (current_step != my_step) {
std::cout << "Thread " << my_step << " is sleeping..." << std::endl;
cond.wait(lk);
std::cout << "Thread " << my_step << " woke up" << std::endl;
}
// Do processing...
std::cout << "Thread " << my_step << " is processing..." << std::endl;
current_step++;
// Signal awaiting task.
cond.notify_one();
std::cout << "Thread " << my_step << " is exiting..." << std::endl;
}
int main() {
constexpr size_t NumThreads = 5;
std::thread threads[NumThreads];
// Create threads.
for (size_t i = 0; i < NumThreads; ++i) {
threads[i] = std::thread(run_step, i);
}
// Wait for all threads to complete.
for (size_t i = NumThreads; i != 0; --i) {
threads[i - 1].join();
}
} |
...