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

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

    std::thread is not necessarily meant to parallize loops. It is meant to be the lowlevel abstraction to build constructs like a parallel_for algorithm. If you want to parallize your loops, you should either wirte a parallel_for algorithm yourself or use existing libraires which offer task based parallism.

    The following example shows how you could parallize a simple loop but on the other side also shows the disadvantages, like the missing load-balancing and the complexity for a simple loop.

      typedef std::vector container;
      typedef container::iterator iter;
    
      container v(100, 1);
    
      auto worker = [] (iter begin, iter end) {
        for(auto it = begin; it != end; ++it) {
          *it *= 2;
        }
      };
    
    
      // serial
      worker(std::begin(v), std::end(v));
    
      std::cout << std::accumulate(std::begin(v), std::end(v), 0) << std::endl; // 200
    
      // parallel
      std::vector threads(8);
      const int grainsize = v.size() / 8;
    
      auto work_iter = std::begin(v);
      for(auto it = std::begin(threads); it != std::end(threads) - 1; ++it) {
        *it = std::thread(worker, work_iter, work_iter + grainsize);
        work_iter += grainsize;
      }
      threads.back() = std::thread(worker, work_iter, std::end(v));
    
      for(auto&& i : threads) {
        i.join();
      }
    
      std::cout << std::accumulate(std::begin(v), std::end(v), 0) << std::endl; // 400
    

    Using a library which offers a parallel_for template, it can be simplified to

    parallel_for(std::begin(v), std::end(v), worker);
    

提交回复
热议问题