简体   繁体   English

如何在 C++ 中多线程 for 循环?

[英]How do I multi-thread a for loop in C++?

How do I multi-thread a for loop in C++?如何在 C++ 中多线程 for 循环? Suppose I want to get such a serial calculation:假设我想得到这样一个串行计算:

// arr is some vector with size n
int sum = 0;
for(int i = 0; i < n; i++)
    sum += arr[i];

so I want to run with 8 threads that run on 1/8 of the array, save partial sum and then add all the partial sums together.所以我想用在数组的 1/8 上运行的 8 个线程运行,保存部分总和,然后将所有部分总和加在一起。 so how do I exactly do this using std::thread?那么我如何使用 std::thread 准确地做到这一点? thanks a lot多谢

You can try something like this你可以试试这样的

    int a = 1; // replace a with your array
    std::atomic <int> sum = 0;
    auto inc = [&](){
    for(int i = 0; i < 10; i++)
        sum += a;
    };
    for(int i = 0; i < 8; i++){
        std::thread(inc).detach();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM