Search⌘ K
AI Features

Threads

Explore the fundamentals of C++ threads, including how to create, manage, and synchronize threads using the <thread> header. Understand thread lifecycle, safe argument passing, and operations like join, detach, sleep, and yield to write efficient multithreaded programs.

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:

C++
//...
#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); // function
HelloFunctionObject helloFunctionObject;
thread t2(helloFunctionObject); // function object
thread 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, and ...