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

前端 未结 6 1272
感动是毒
感动是毒 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:47

    Define macro using std::thread and lambda expression:

    #ifndef PARALLEL_FOR
    #define PARALLEL_FOR(INT_LOOP_BEGIN_INCLUSIVE, INT_LOOP_END_EXCLUSIVE,I,O)          \                                                               \
        {                                                                               \
            int LOOP_LIMIT=INT_LOOP_END_EXCLUSIVE-INT_LOOP_BEGIN_INCLUSIVE;             \
            std::thread threads[LOOP_LIMIT]; auto fParallelLoop=[&](int I){ O; };       \
            for(int i=0; i

    usage:

    int aaa=0; // std::atomic aaa;
    PARALLEL_FOR(0,90,i,
    {
        aaa+=i;
    });
    

    its ugly but it works (I mean, the multi-threading part, not the non-atomic incrementing).

提交回复
热议问题