From af6fa97b35c188a9c61f91ab6a2ac8ff67ed888a Mon Sep 17 00:00:00 2001
From: Erik Strand <erik.strand@cba.mit.edu>
Date: Sun, 25 Nov 2018 20:50:10 -0500
Subject: [PATCH] Add mutex example

---
 mutex.cpp  | 26 ++++++++++++++++++++++++++
 thread.cpp |  3 ++-
 2 files changed, 28 insertions(+), 1 deletion(-)
 create mode 100644 mutex.cpp

diff --git a/mutex.cpp b/mutex.cpp
new file mode 100644
index 0000000..09a9dce
--- /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 0494f73..f3db875 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) {
-- 
GitLab