From 17e9aa3a1061d02c52a5275328188aa4bd86d8e0 Mon Sep 17 00:00:00 2001 From: Erik Strand <erik.strand@cba.mit.edu> Date: Sun, 25 Nov 2018 17:53:32 -0500 Subject: [PATCH] Add some more basic examples to thread.cpp --- thread.cpp | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/thread.cpp b/thread.cpp index 94ab3f5..0494f73 100644 --- a/thread.cpp +++ b/thread.cpp @@ -1,13 +1,30 @@ #include <thread> #include <iostream> -void thread_method() { - std::cout << "hello thread" << std::endl; +void thread_method(int i) { + std::cout << "hello thread " << i << std::endl; } +struct ThreadObject { + void operator()(int i) const { + std::cout << "hello object " << i << std::endl; + } +}; + int main() { - std::thread thread(thread_method); - thread.join(); + // Note that no care is taken to avoid race conditions around the global object std::cout. + // Arguments are copied into 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) { + std::cout << "hello lambda " << i << std::endl; + }, 3); + + // Without these, the main thread could terminate before the children complete. + function_thread.join(); + object_thread.join(); + lambda_thread.join(); + return 0; } -- GitLab