thread在我可以分离之前完成

thread在我可以分离之前完成

本文介绍了std :: thread在我可以分离之前完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建了一个std :: thread,该线程在可以调用detatch()之前终止,则预期的行为是什么?是否应该由于joinable已经为假而抛出异常?

If I create an std::thread that terminates before I am able to call detatch() on it, what is the expected behavior? Should an exception be thrown due to the fact that joinable is already false?

如果是这样,那么有没有办法创建一个初始化为分离状态的线程,这样我就可以避免此错误?

If this is so, then is there a way to create a thread which is initialized into a detached state so that I can avoid this error?

示例:

void func()
{
    // do something very trivial so that it finishes fast
    int a = 1;
}

void main()
{
    thread trivial(func);
    trivial.detach();
}

我意识到在实践中产生一个线程来进行琐碎的工作实际上是不实际的,但是我确实碰到了这种行为,并且我很好奇是否有解决方法...

I realize that it isn't really practical to spawn a thread to do trivial work in practice, however I did manage to run into this behavior, and I was curious to know if there is a way around it...

推荐答案

联接和分离具有相同的要求,它们必须是可联接的.因此,我认为进行可合并检查就足够了.

Join and detach have the same requirement, they have to be joinable. So I think doing the joinable check should suffice.

If(trivial.joinable())
    trivial.detach();

文档状态:

所以我的猜测是,分离的线程将立即不复存在.但肯定可以创建.

So my guess would be that the detached thread will cease to exist right away. But it definitily can be created.

注意:最好在加入或分离线程之前始终调用joinable().

Note:It's good practice to always call joinable() before joining or detaching a thread.

这篇关于std :: thread在我可以分离之前完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 09:09