C - C++ Threads - Create Background Tasks

You can make a std::thread run in the background by calling std::thread::detach() on it.


#include <iostream>
#include <string>
#include <thread>
#include <functional>
 
void Count()
{
  for (int i=0; i<100; i++)
  {
    std::cout << "counter at: " << i << std::endl;
  }
}
 
int main()
{
  std::thread t1(Count);
  std::this_thread::sleep_for(std::chrono::milliseconds(10));
  t1.detach();
  return 0;
}

NOTE: The 10 millisecond sleep is needed otherwise no output will be displayed.

The reason for this is that the main thread terminates before the “Count” thread has had an opportunity to run.