c++ - std::thread 未定义行为

标签 c++ multithreading

下面的代码是否可能产生未定义的行为?

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/

相关文章:

c++ - 如何在 OSX 上用 C++ 编写旋转光标?

C++ Opencv 不同分辨率相机标定

c++ - 将 CSocket 传递给 std::thread

vb.net - 需要有关 VB.Net 多线程选项的建议

c++ - 什么是 C 中指向 'array of characters' 的指针?

c++ - 来自 cython wiki 的 Hello World 不起作用

C++ vector.begin() 和 vector[0]

ios - 如何使用 Kotlin-Multiplatform 在 iOS 应用程序的后台线程中运行任务?

android - 从线程更改 TextView 文本

c - NtQueryInformationThread 在我的代码中总是失败?