0

So assuming I have a thread running, and I want the rest of the code outside of the thread to run without having to worry about the thread's join() function to block the code. Will it be safe to do the following:

thread someThread([&someVariable]
{ 
    ThreadCode(someVariable);
    
    someThread.detach();
});

while(1)
{
     RestOfMyCode();
}

Currently I use flags to check if a thread is still running or not, but I feel the above code will be easier to read/troubleshot

  • 6
    Detaching a thread rather than using `join` does not relieve you of the need to coordinate thread termination, it just makes the effort orders of magnitude more difficult and error prone. – Eljay Jun 22 '23 at 12:13

3 Answers3

2

Using detach in general is a sign of bad design. See this topic. Apart from that, your code might lead to std::terminate if your thread will be late to call detach on itself after main returns. See this example.

If you want to "fire and forget", just keep your std::thread in some context accessible from your main routine, and simply join it whenever you finished doing your main task. In case thread finishes earlier, not a big deal. In case it is still running, your main program will just wait for it, which it should probably do anyway, because what's the point of keeping a child thread whose parent is already dead, along with its resources.

pptaszni
  • 5,591
  • 5
  • 27
  • 43
0

The way you are detaching the thread might lead to a dangling reference as the main thread may complete its execution before the thread is fully executed. From my experience you should use a shared flag variable for a better approach

0

The code is correct, although the application design might be not good. The POSIX pthread_detach() manual has the example of its usage in the calling thread:

pthread_detach(pthread_self());

It's what your code does.

273K
  • 29,503
  • 10
  • 41
  • 64