且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

做多线程的***方法是什么?

更新时间:2023-10-24 08:17:28

您可能要考虑TBB库( http://(threadingbuildingblocks.org/),它使用基于任务的并行性来均衡各个迭代的执行时间可能存在的差异.您的代码将如下所示(使用C ++ 11)

You may want to consider the TBB library (http://threadingbuildingblocks.org/) which uses task-based parallelism to even out possible differences in the execution time of individual iterations. Your code would look like this (using C++11)

tbb::parallel_for(0,n,[](int i){
  funcA(i);
  funcB(i);
});

当必须用普通函子替换lambda时,也可以使用C ++ 03.使用TBB,您还可以将其编码为管道.

You can also use C++03, when you must replace the lambda with an ordinary functor. With TBB you can also code it as a pipeline.

或者,使用OpenMP,您的代码很简单

Alternatively, with OpenMP, your code is simply

#pragma omp parallel for
for(int i=0;i<n;++i) {
  funcA(i);
  funcB(i);
}

但这需要您的编译器支持OpenMP(clang不支持),而OpenMP与C ++ 11不能很好地配合.

but this requires your compiler to support OpenMP (clang doesn't), which doesn't mesh well with C++11.