线程可能会分离自己,释放其资源。如果析构函数看到线程可以连接,即仍在运行,那么让它加入。如果线程到达末端,则自行分离。可能的竞态条件:is_joinable()在析构函数中返回true - 线程自行分离 - 析构函数加入并失败。因此,使用互斥守护线程的死亡:
struct ThreadContainer
{
std::mutex threadEndMutex;
std::thread theThread;
ThreadContainer()
: theThread([=]()
{
/* do stuff */
// if the mutex is locked, the destructor is just
// about to join, so we let him.
if (threadEndMutex.try_lock())
theThread.detach();
})
{}
~ThreadContainer()
{
// if the mutex is locked, the thread is just about
// to detach itself, so no need to join.
// if we got the mutex but the thread is not joinable,
// it has detached itself already.
if (threadEndMutex.try_lock() && theThread.is_joinable())
theThread.join();
}
};
PS: 你甚至不需要调用is_joinable,因为如果分离线程本身,它永远不会解锁互斥和try_lock失败。
PPS: 而非互斥体,你可以使用std :: atomic_flag:
struct ThreadContainer
{
std::atmoic_flag threadEnded;
std::thread theThread;
ThreadContainer()
: threadEnded(ATOMIC_FLAG_INIT)
, theThread([=]()
{
/* do stuff */
if (!threadEnded.test_and_set())
theThread.detach();
})
{}
~ThreadContainer()
{
if (!threadEnded.test_and_set())
theThread.join();
}
};
编辑。任何帮助都将是非常感谢 –
你可能想看看['std :: notify_all_at_thread_exit'](http://en.cppreference.com/w/cpp/thread/notify_all_at_thread_exit)。 –
@JoachimPileborg谢谢你将会看到它 –