...
This compliant solution eliminates the race condition by joining the threads before the lock's destructor is invoked:
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <mutex>
#include <thread>
const size_t max_threads = 10;
void do_work(size_t i, std::mutex *lockp)
{
std::lock_guard<std::mutex> guard(*lockp);
// Access data protected by the lock.
}
void run_threads(void)
{
std::thread threads[max_threads];
std::mutex lock;
for (size_t i = 0; i < max_threads; ++i) {
threads[i] = std::thread(do_work, i, &lock);
}
for (size_t i = 0; i < max_threads; ++i) {
threads[i].join();
}
} |
...