User Tools

Site Tools


c:c_threads:create_background_tasks

This is an old revision of the document!


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;
}
c/c_threads/create_background_tasks.1614942262.txt.gz · Last modified: 2021/03/05 11:04 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki