← Patterns

Create a thread

123456789101112131415161718#include <thread> #include <string> #include <functional> void func(std::string str, int& x); void do_something(); int main() { std::string str = "Test"; int x = 5; std::thread t{func, str, std::ref(x)}; do_something(); t.join(); }

This pattern is licensed under the CC0 Public Domain Dedication.

Requires c++11 or newer.

Intent

Execute code on a separate thread.

Description

On line 13, we create a std::thread object t, which represents a thread of execution. When constructing t, we pass func as the function to execute on that thread.

To pass arguments to func, we have passed them as additional arguments to std::thread’s constructor. Notice that to pass an argument by reference, it must be wrapped in a std::reference_wrapper — to do this, we use the std::ref helper function. For const references, use std::cref.

After creating the thread, the remainder of main continues to execute as normal. At the same time, function func begins executing in the newly-created thread. This means that the bodies of func and main will be executing concurrently. They may be executed in parallel if the system supports parallel execution.

On line 17 we call t’s join member function. This causes main’s thread to block until the thread finishes execution (which is when func returns). Once join returns, execution continues in main’s thread.

Note: A thread must be either joined or detached before destruction, or std::terminate will be called.

Note: If func propagates an exception, std::terminate will be called.

Contributors

  • Joseph Mansfield
  • Mark A. Gibbs

Last Updated

09 December 2017

Source

Fork this pattern on GitHub

Share