User Tools

Site Tools


c:c_threads:create_background_tasks

C - C++ Threads - Create Background Tasks

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

  • Once detached, a thread continues to run in the background and cannot be communicated with or waited upon to complete.
  • When you detach a thread, the ownership and control passes over to the C++ Runtime Library, which ensures that the resources allocated to the thread are deallocated once the thread exits.

#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.

c/c_threads/create_background_tasks.txt · Last modified: 2021/03/05 16:40 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki