为什么这条线不知道它是谁
Why does this thread not know who it is?
以下代码(在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();
}
}
相关文章:
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 我不知道这条线是做什么的
- 反转字符串.不知道为什么这个逻辑是错误的.C++
- 从 stdio 获取一行空格分隔的整数,而不知道它们是多少 (C++)
- 必须具有泛型接口的函数,但必须根据传递的子类(不知道它们是什么!)以不同的行为 - C++
- *(flow + i*n + j) 在 C 中是什么意思?我不知道这个话题叫什么
- 合成错误不知道为什么会发生这种情况,请检查一下并告诉我这是我的编码还是视觉工作室
- 我不知道这是什么意思 (x^y) ?在 C++ 中
- 当我打印字符串时,我不知道它是什么输出
- Clang说is_same_v<int,double>的用法不是constexpr,不知道它怎么不是
- 我不断收到分段错误,但不知道是什么原因造成的
- 不知道这个无限循环是从哪里来的
- 我试着了解方法覆盖是如何工作的,不知道为什么输出 2
- 库特是空的,我不知道为什么
- C++98 中获取并继续调用当前类不知道的类方法的最简单方法是什么?
- 在std ::访问中获得主动价值,而又不知道哪个值是活动的
- 我不知道它是如何工作的表[+1]?
- 我不知道如何让我的程序使用局部变量而不是全局变量
- 视觉错误类 c++ 类。 不知道它是什么
- 为什么这条线不知道它是谁