thread

Threads allow multiple functions (including lambda functions and functions with bound arguments) to run simultaneously. Depending on your computer system, and how many threads are running, these threads may run in parallel or they may stop and start to give the illusion of parallel execution.

Create a thread by passing a function or a callable object (eg. an object with a function with signature void operator(), or a lambda function) to its constructor. Once the thread has been created it will start running. Call thread. join() on the parent thread to synchronize the parent thread with the termination of the child.

Threads can be detached after they are created. Detached threads are no longer owned by the thread object that launched them and do not need to be joined.

#include <iostream>

#include <thread>

void task(unsigned thread_id)
{
}

struct Callable final
{
   void operator() (void)
   {
   }
}
;

int main(int argc, char ** argv)
{
   {
   
   ::std::thread
      thread( task, 0u );
   
   //
   // Get the ID of the thread:
   //
   
   ::std::cout << "Thread ID: "
               << thread.get_id()
               << ::std::endl
                  ;
   
   thread.join();
   
   }
   
   {
   
   Callable
      object;
   
   ::std::thread
      thread( object );
   
   thread.join();
   
   }
   
   {
   
   ::std::thread
      thread( task, 2u );
   
   //
   // Get the ID of the thread:
   //
   
   ::std::cout << "Thread ID: "
               << thread.get_id()
               << ::std::endl
                  ;
   
   thread.detach();
   
   // thread.join();       // Throws ::std::system_error
   
   }
   
   {
   
   ::std::thread
      thread( task, 3u );
   
   ::std::cout << "Is jointable: "
               << thread.joinable()       // True
               << ::std::endl
                  ;
   
   thread.join();
   
   ::std::cout << "Is jointable: "
               << thread.joinable()       // False
               << ::std::endl
                  ;
   
   }
   
   return 0;
}
Output:
Thread ID: 140338842826304 Is jointable: 1 Is jointable: 0