下面的代码是否可能产生未定义的行为?
unsigned int total_threads = 10;
vector<thread> t(total_threads);
unsigned int *nums = (unsigned int*)calloc(total_threads, sizeof(int));
for(unsigned int i = 0; i < 1000; i++)
{
for(unsigned int j = 0; j < total_threads; j++)
t[j] = thread(func_, std::ref(nums[j]));
for(unsigned int j = 0; j < total_threads; j++)
t[j].join();
for(unsigned int j = 0; j < total_threads; j++)
{
cout << nums[j] << " ";
nums[j] = 0;
}
}
最佳答案
是的,因为 calloc 可能会失败。检查返回值或使用 std::vector 。
关于c++ - std::thread 未定义行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21737887/