Boost::this_thread::get_id在exit()调用期间不返回id

boost::this_thread::get_id not returning id during exit() call

本文关键字:id 调用 返回 thread this get Boost exit      更新时间:2023-10-16

我有一个相当简单的c++应用程序,其中有两个线程——主线程和一个工作线程。工作线程等待通过网络发送的数据包,当接收到断开连接时,调用exit(0)。

这会导致负责线程的类的析构函数运行。这个析构函数通常从主线程运行,并导致工作线程(如果正在运行)停止,然后调用join来等待它停止。下面是析构函数的代码:

if( m_thread.get_id() == boost::this_thread::get_id() )
{
    return;
}
if ( m_thread.joinable() )
{
    m_runThread = false;
    m_thread.join();
}

我的问题是

这行
if( m_thread.get_id() == boost::this_thread::get_id() )

返回false,尽管我可以从调试中看出这段代码肯定是在m_thread引用的线程上运行的。

在对此进行了更多的研究之后,boost::this_thread::get_id()此时返回的id为0。然而,visual studio调试器和win32 API函数GetCurrentThreadId仍然能够正确识别线程id。

有人能解释一下吗?在应用程序关闭期间是否不支持boost::this_thread,可能是因为它在此时已经被销毁了?

你不应该在线程中调用exit !这个函数退出整个进程,而不仅仅是线程。从线程函数返回。

exit(0)强制所有线程退出。当您调用m_thread.get_id()时,m_thread引用的线程可能已经被破坏。