CppCommon  1.0.4.1
C++ Common Library
threads_mutex.cpp

Mutex synchronization primitive example

#include "threads/mutex.h"
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
int main(int argc, char** argv)
{
std::cout << "Press Enter to stop..." << std::endl;
// Start some threads
std::atomic<bool> stop(false);
std::vector<std::thread> threads;
for (int thread = 0; thread < 4; ++thread)
{
threads.emplace_back([&lock, &stop, thread]()
{
while (!stop)
{
// Use locker with mutex to protect the output
std::cout << "Random value from thread " << thread << ": " << rand() << std::endl;
}
});
}
// Wait for input
std::cin.get();
// Stop threads
stop = true;
// Wait for all threads
for (auto& thread : threads)
thread.join();
return 0;
}
Locker synchronization primitive.
Definition: locker.h:23
Mutex synchronization primitive.
Definition: mutex.h:30
Mutex synchronization primitive definition.