Thread class
The thread
class is the core of the entire threading API; it wraps the underlying operating system's threads, and provides the functionality we need to start and stop threads.
This functionality is made accessible by including the <thread>
header.
Basic use
Upon creating a thread it is started immediately:
#include <thread> void worker() { // Business logic. } int main () { std::thread t(worker); return 0; }
This preceding code would start the thread to then immediately terminate the application, because we are not waiting for the new thread to finish executing.
To do this properly, we need to wait for the thread to finish, or rejoin as follows:
#include <thread> void worker() { // Business logic. } int main () { std::thread t(worker); t.join(); return 0; }
This last code would execute, wait for the new thread to finish, and then return.
Passing parameters
It's also possible to pass parameters to a new thread. These parameter...