C++ - For 循环有时不会停止 - 多线程

标签 c++ multithreading

我在用 C++ 开发一个函数时遇到了一个相当晦涩的问题。我在拆分的巨大数组上使用多线程来提高处理速度。

我的代码:

    std::mutex mu;
    std::vector<std::thread> threads;
    int N_THREADS = std::thread::hardware_concurrency();

    std::vector<std::vector<KP>> queryKPs_split = splitVector(queryKPs, N_THREADS);
    std::cout << queryKPs_split.size() << std::endl;

    for (int thr = 0; thr < N_THREADS; thr++) {
        std::cout << thr << " " << N_THREADS << std::endl;

        threads.push_back(std::thread([&]() {
            for (auto &kp : queryKPs_split.at(thr)) { ... }});
    }

问题是有时(并非总是)我在 queryKPs_split.at(thr) 处的 queryKPs_split 上遇到超出范围的异常。原因是 thr 的值上升到 8,而它应该停止在 7,如 for 循环 (N_THREADS = 8) 中所述。有谁知道为什么会发生这种情况?

下面是异常出现前运行不成功的结果:

8
0 8
1 8
2 8
3 8
4 8
5 8
6 8
7 8

提前致谢!

大卫

最佳答案

您正在通过引用捕获 thr,因此随着 for 循环增加变量,您的线程将看到对它的更改。改为按值捕获它:

threads.push_back(std::thread([&, thr]() {
            for (auto &kp : queryKPs_split.at(thr)) { ... }});

关于C++ - For 循环有时不会停止 - 多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50491577/

相关文章:

c++ - Ctypes 在使用 CMake 创建的共享库中找不到符号

c++ - [] 运算符的正确模拟

c++ - 静态变量,单独编译

java - 设置正确的多线程

c# - 确保多线程应用程序中的ProcessingQueue.Count正确

c++ - CTreeCtrl 中的字体更改后未调整项目大小

Java多线程同步问题

asp.net - WCF 请求处理线程敏捷吗?

Java - 多线程增量

c++ - 整数的快速排序算法