| [ Web Proxy ] |
| Viewing: https://cpppatterns.com/patterns/create-thread.html | [Back] [Original] |
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.
Execute code on a separate thread.
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::threads 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 ts join member
function. This causes mains thread to block until the thread
finishes execution (which is when func returns). Once join
returns, execution continues in mains 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.
09 December 2017
Feel like contributing? This website is generated from a git repository. If you have something to add or have noticed a mistake, please fork the project on GitHub.
| Web Proxy Viewer | New URL | Original Page |