Sometimes, you might want to make a thread run indefinitely in the background by not binding it to its creation scope. Even though calling
detach()
on an std::thread
or std::jthread
object would satisfy this need, it is not the easiest way to do it:
there will be no direct way to monitor and communicate with the detached thread, the std::thread
or std::jthread
object is
no longer associated to any thread.
An easier alternative to satisfy this need is giving the thread a global scope. This way the thread will run as long as the program does. The
thread will not be bound to any scope. It is also possible to do it by giving the std::thread
or std::jthread
a scope that
is big enough for your use case. For example, the program’s main function.
Noncompliant code example
void backgroundTask();
void startBackgroundTask(){
// Assume you want the thread to run after the end of startBackgroundTask
std::jthread backgroundThread(backgroundTask);
backgroundThread.detach(); // Noncompliant
}
Compliant solution
void backgroundTask();
std::jthread backgroundThread;
void startBackgroundTask(){
// Assume you want the thread to run after the end of startBackgroundTask
backgroundThread = std::move(std::jthread{backgroundTask});
}