diff --git a/thread.cpp b/thread.cpp index 94ab3f510978d34d5d82715188906ab385516823..0494f73831701f5ba08fb4b4584e48e65b5553fe 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; }