英文:
Is it safe to detach a thread within it's own callback?
问题
假设我有一个正在运行的线程,并且我希望线程外的其余代码能够在不担心线程的join()函数阻塞代码的情况下运行。以下操作是否安全:
thread someThread([&someVariable]
{
ThreadCode(someVariable);
someThread.detach();
});
while(1)
{
RestOfMyCode();
}
目前我使用标志来检查线程是否仍在运行,但我觉得上述代码会更容易阅读/排错。
英文:
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
答案1
得分: 2
在一般情况下,使用detach
是糟糕设计的迹象。请参考这个主题。除此之外,如果你的线程在main
返回后才调用detach
,可能会导致std::terminate
。请参考这个示例。
如果你想要“点火并忘记”,只需将你的std::thread
保留在可以从主例程访问的上下文中,然后在完成主要任务后简单地join
它即可。如果线程提前完成,也没有什么大不了的。如果它仍在运行,你的主程序将等待它,这可能本就是应该做的,因为保留一个子线程,而其父线程已经死亡,也无法访问其资源,这有何意义。
英文:
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.
答案2
得分: 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
答案3
得分: 0
代码是正确的,尽管应用程序设计可能不是很好。POSIX pthread_detach()
手册中有在调用线程中使用它的示例:
pthread_detach(pthread_self());
这就是你的代码所做的。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论