jthread

jthreads differ from threads in two key ways as follows:

#include <thread>

void worker(unsigned thread_id)
{
   return;
}

int main(int argc, char ** argv)
{
   {
   
   ::std::jthread
      thread( worker, 0u );
   
   // thread.join() is automatically called by the dtor
   
   }
   
   return 0;
}

To stop a jthread, add a stop_token to the argument list of the thread entrypoint. The stop_token can be used to request an execution stop.

The token reveals whether or not a stop has been requested:

#include <iostream>

#include <thread>

void worker
   (
   ::std::stop_token
      stop
         ,
   unsigned
      thread_id
   )
{
   unsigned
      index = 0u;
   
   while
      (
         //
         // Continue until request_stop is called:
         //
      not stop.stop_requested()
      )
   {
      ::std::cout << index++ << " ";
      
      ::std::cout.flush();
      
      ::std::this_thread::sleep_for
         (
         ::std::chrono::seconds(1)
         )
         ;
   }
   
   return;
}

int main(int argc, char ** argv)
{
   ::std::jthread
      thread( worker, 0u );
   
   ::std::this_thread::sleep_for
      (
      ::std::chrono::milliseconds(5100)
      )
      ;
   
   thread.request_stop();           // Request stop
   
   ::std::cout << ::std::endl;
   
   return 0;
}
Output:
0 (pause) 1 (pause) 2 (pause...) 3 4 5