Select Git revision
-
Erik Strand authoredErik Strand authored
mutex.cpp 625 B
#include <array>
#include <thread>
#include <iostream>
int main() {
constexpr auto n_threads = 10u;
std::array<std::thread, n_threads> threads;
std::mutex cout_mutex;
const auto hello = [&cout_mutex](int i) {
// Uncommenting this line will randomly interleave all the threads' outputs.
std::lock_guard<std::mutex> cout_lock(cout_mutex);
std::cout << "Hello from thread " << i << '\n';
};
for (auto i = 0u; i < n_threads; ++i) {
threads[i] = std::thread(hello, i);
}
for (auto i = 0u; i < n_threads; ++i) {
threads[i].join();
}
return 0;
}