带升压的平行部分

时间:2013-02-08 18:09:15

标签: c++ boost openmp

我正在寻找一种方法来使用boost线程来并行运行代码块,而无需创建工作函数或函子。我想要类似于OpenMP的并行部分构造:

#pragma omp parallel sections
{
   #pragma omp section
   {
      ... do some work
   }
   #pragma omp section
   {
      ... do some more
   }
}

有没有办法使用boost来实现这个目标?

1 个答案:

答案 0 :(得分:2)

如果您可以使用C ++ 11, lambda 表达式将非常有用。 (lambda实际上是一种仿函数,但下面的代码看起来像OpenMP版本?)

#include <boost/thread.hpp>

{
  boost::thread th1([&]() {
    // ... do some work (thread#1)
  });
  boost::thread th2([&]() {
    // ... do some more (thread#2)
  });
  // wait for two tasks completion
  th1.join();
  th2.join();
}

thread_group版本:

{
  boost::thread_group pool;
  pool.create_thread([&]() {
    // ... do some work (thread#1)
  });
  pool.create_thread([&]() {
    // ... do some more (thread#2)
  });
  // wait for two tasks completion
  pool.join_all();
}