为什么这条线不知道它是谁

Why does this thread not know who it is?

本文关键字:是谁 不知道 为什么      更新时间:2023-10-16

以下代码(在Visual Studio 2013下)在断言中失败。有人能解释一下为什么会这样吗?

#include <thread>
#include <cassert>
std::thread t;
void threadTask()
{
   assert(t.get_id() == std::this_thread::get_id());
}
int main()
{
    for (int i = 0; i < 1000; ++i)
    {
        t = std::thread(threadTask);
        t.join();
    }
}

我正在寻找一种方法来检查从指定线程调用函数

线程可以在std::thread构造函数退出回调用者之前开始运行,因此assert()可能在t变量被分配新值之前被调用。在第一次循环迭代中,这意味着t可能未定义。在随后的迭代中,这意味着t可能仍然引用前一个线程。

线程需要等到t被赋值后才能可靠地使用t。例如,通过使用std::mutex:

保护t
#include <thread>
#include <mutex>
#include <cassert>
std::thread t;
std::mutex m;
void threadTask()
{
   {
   std::lock_guard<std::mutex> l(m);
   assert(t.get_id() == std::this_thread::get_id());
   }
   ...
}
int main()
{
    for (int i = 0; i < 1000; ++i)
    {
        {
        std::lock_guard<std::mutex> l(m);
        t = std::thread(threadTask);
        }
        t.join();
    }
}