C++ 2011 : std::thread : simple example to parallelize a loop?

前端 未结 6 1269
感动是毒
感动是毒 2020-12-13 07:14

C++ 2011 includes very cool new features, but I can\'t find a lot of example to parallelize a for-loop. So my very naive question is : how do you parallelize a simple for lo

6条回答
  •  星月不相逢
    2020-12-13 07:37

    AFAIK the simplest way to parallelize a loop, if you are sure that there are no concurrent access possible, is by using OpenMP.

    It is supported by all major compilers except LLVM (as of August 2013).

    Example :

    for(int i = 0; i < n; ++i)
    {
       tab[i] *= 2;
       tab2[i] /= 2;
       tab3[i] += tab[i] - tab2[i];
    }
    

    This would be parallelized very easily like this :

    #pragma omp parallel for
    for(int i = 0; i < n; ++i)
    {
       tab[i] *= 2;
       tab2[i] /= 2;
       tab3[i] += tab[i] - tab2[i];
    }
    

    However, be aware that this is only efficient with a big number of values.

    If you use g++, another very C++11-ish way of doing would be using a lambda and a for_each, and use gnu parallel extensions (which can use OpenMP behind the scene) :

    __gnu_parallel::for_each(std::begin(tab), std::end(tab), [&] () 
    {
        stuff_of_your_loop();
    });
    

    However, for_each is mainly thought for arrays, vectors, etc... But you can "cheat" it if you only want to iterate through a range by creating a Range class with begin and end method which will mostly increment an int.

    Note that for simple loops that do mathematical stuff, the algorithms in #include and #include can all be parallelized with G++.

提交回复
热议问题