Threads
Let's dive into C++ threads and their lifecycle.
We'll cover the following...
To use the multithreading interface of C++ you need the header <thread>.
Creation
A thread std::thread
represents an executable unit. This executable unit, which the thread immediately starts, gets its work package as a callable unit. A callable unit can be a function, a function object, or a lambda function:
//...#include <iostream>#include <thread>//...using namespace std;void helloFunction(){cout << "function" << endl;}class HelloFunctionObject {public:void operator()() const {cout << "function object" << endl;}};int main{thread t1(helloFunction); // functionHelloFunctionObject helloFunctionObject;thread t2(helloFunctionObject); // function objectthread t3([]{ cout << "lambda function"; }); // lambda function}
Lifetime
The creator of a thread has to take care of the lifetime of its created thread. The executable unit of the created thread ends with the end of the callable. Either the creator is waiting until the created thread t
is done (t.join())
or the creator detaches itself from the created thread: t.detach()
. A thread t
is joinable if no operation t.join()
or t.detach()
was performed on it. A joinable thread calls in its destructor the exception std::terminate
...