c++ - C++中的多线程: The correct way to join threads

标签 c++ multithreading c++11 thread-safety

我是多线程的新手,所以任何建议都将不胜感激。以下程序接收一个整数 vector (例如1 2 3 4 5 6 7),并将每个整数作为线程进行处理。我想知道连接线程的方法是否正确,是否可以进行任何改进。
希望我的解释清楚!这是我的代码段。这不是完整的代码,我只是确保我走对了路:

    //vector's name is 'inputs' and it contains integers

    for (int unsigned i = 0; i < inputs.size(); i++) {
        thread thread_obj(thread_function, inputs.at(i));  
        thread_obj.detach();
        
    }
    
    for (int unsigned i = 0; i < inputs.size(); i++) {
      thread_obj.join();
    }
   
    

最佳答案

您的代码具有未定义的行为,所以不,这是不正确的。这里的问题是,只有当join()joinable()时,您才能调用true,并且因为您调用了detach(),所以joinable()将返回false

好消息是这确实是一个简单的修复。您只需要删除对detach的调用即可。要完成代码,只需填充一个线程 vector ,然后像这样将它们全部加入

std::vector<std::thread> threads;
threads.reserve(inputs.size());
for (int unsigned i = 0; i < inputs.size(); i++) {
    threads.push_back(std::thread{thread_function, inputs.at(i)};  
}
// now all threads are running, or waiting to run
for (int unsigned i = 0; i < inputs.size(); i++) {
    threads[i].join();
}
// now all threads have been joined

关于c++ - C++中的多线程: The correct way to join threads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59460494/

相关文章:

c++ - Microsoft Detours - DetourUpdateThread?

java - 在 HTTPServer 的 Executors.newFixedThreadPool 中设置可用的处理器

c++ - 使用 std::make_shared() 的数据缓存影响

c++ - 输入所有子文件夹 - 递归

c++ - 线程输入问题

c++11 - 为什么 clang++ 缺少转发列表?

c++ - std::move 给出了将 std::string 移动到另一个线程的错误

c++ - 如何知道 sigsetjmp 或 siglongjmp 是否失败?

c++ - Linux 守护进程不工作

c++ - 为什么编译器允许缩小转换