diff --git a/mutex.cpp b/mutex.cpp new file mode 100644 index 0000000000000000000000000000000000000000..09a9dce67983bd280fce167ba6346f736f1e54c4 --- /dev/null +++ b/mutex.cpp @@ -0,0 +1,26 @@ +#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; +} + diff --git a/thread.cpp b/thread.cpp index 0494f73831701f5ba08fb4b4584e48e65b5553fe..f3db87505930ea9d195c695f44a9a997fb25f1bc 100644 --- a/thread.cpp +++ b/thread.cpp @@ -13,7 +13,8 @@ struct ThreadObject { int main() { // Note that no care is taken to avoid race conditions around the global object std::cout. - // Arguments are copied into the child threads. + // See mutex.cpp for a solution. + // Note that arguments are passed by value to the child threads. auto function_thread = std::thread(thread_method, 1); auto object_thread = std::thread(ThreadObject(), 2); auto lambda_thread = std::thread([](int i) {