做多线程的最佳方法是什么? [英] What is the best way of doing multithreading?
问题描述
我有以下代码:
for(int i=0;i<n;i++){
funcA(i);
funcB(i);
}
我想使用多线程来实现它,而且我认为有两种方法可以实现(在这两种情况下,每个线程都具有[0,n]的子范围):
I want to implement it using multi-threads, and i think there are two ways to do so (in both, each thread takes a sub-range of [0, n]):
1)创建一个同时执行这两个功能的线程类.
1) Create a thread class that executes both functions.
2)创建两个线程类:第一个执行funcA(),第二个执行funcB(),例如每个线程都有自己的循环,如下所示:
2) Create two thread classes: the first executes funcA() and the second executes funcB(), such as each one has its own loop, like this:
for(int i=0;i<n;i++){
funcA(i);
}
for(int i=0;i<n;i++){
funcB(i);
}
哪个是最好的?还是等价的?
Which one is the best? or are they equivalent?
推荐答案
您可能要考虑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.
这篇关于做多线程的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!