为了优化我正在制作的一些库的执行,我必须并行化一些计算。不幸的是,我不能为此使用 openmp,所以我正在尝试使用 boost::thread 做一些类似的替代方案。有人知道这样的实现吗?我在线程之间共享变量时遇到特殊问题(将变量定义为openmp的“共享”和“私有”)。有什么建议吗?
1 回答
据我所知,除了 OpenMP 之外,您必须明确地执行此操作。
例如,如果我们在 OpenMP 中有一个并行循环
int i;
size_t length = 10000;
int someArray[] = new int[length];
#pragma omp parallel private(i)
{
#pragma omp for schedule(dynamic, 8)
for (i = 0; i < length; ++i) {
someArray[i] = i*i;
}
}
您必须将逻辑分解为可以处理问题的子范围的“通用”循环,然后显式安排线程。然后每个线程将处理整个问题的一部分。通过这种方式,您可以显式声明“私有”变量——进入 subProblem 函数的变量。
void subProblem(int* someArray, size_t startIndex, size_t subLength) {
size_t end = startIndex+subLength;
for (size_t i = startIndex; i < end; ++i) {
someArray[i] = i*i;
}
}
void algorithm() {
size_t i;
size_t length = 10000;
int someArray[] = new int[length];
int numThreads = 4; // how to subdivide
int thread = 0;
// a vector of all threads working on the problem
std::vector<boost::thread> threadVector;
for(thread = 0; thread < numThreads; ++thread) {
// size of subproblem
size_t subLength = length / numThreads;
size_t startIndex = subLength*thread;
// use move semantics to create a thread in the vector
// requires c++11. If you can't use c++11,
// perhaps look at boost::move?
threadVector.emplace(boost::bind(subProblem, someArray, startIndex, subLength));
}
// threads are now working on subproblems
// now go through the thread vector and join with the threads.
// left as an exercise :P
}
以上是许多调度算法之一——它只是将问题分成与线程一样多的块。
OpenMP 方式更复杂——它将问题分成许多小块(在我的示例中为 8 个),然后使用工作窃取调度将这些块提供给线程池中的线程。实现 OpenMP 方式的困难在于您需要等待工作的“持久”线程(线程池)。希望这是有道理的。
一种更简单的方法是在每次迭代中执行异步(为每次迭代安排一项工作)。如果每次迭代都非常昂贵并且需要很长时间,这可以工作。但是,如果它是具有多次迭代的小块工作,则大部分开销将用于调度和线程创建,从而使并行化变得无用。
总之,根据您的问题,有很多方法可以安排工作,您可以自行决定哪种方法最适合您的问题。
TL;DR: 如果您提供“子范围”功能,请尝试为您安排的 Intel Threading Building Blocks(或 Microsoft PPL):
http://cache-www.intel.com/cd/00/00/30/11/301132_301132.pdf#page=14