Skip to content
Snippets Groups Projects
Commit af6fa97b authored by Erik Strand's avatar Erik Strand
Browse files

Add mutex example

parent 7c15bf3d
No related branches found
No related tags found
No related merge requests found
#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;
}
......@@ -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) {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment