【发布时间】:2015-01-20 06:15:01
【问题描述】:
我正在研究一种递归算法,我们希望对其进行并行化以提高性能。
我使用 Visual c++ 12.0 和
如果我做错了什么以及我应该对代码进行哪些更正,请告诉我。
这是我的代码
void nonRecursiveFoo(<className> &data, int first, int last)
{
//process the data between first and last index and set its value to true based on some condition
//no threads are created here
}
void recursiveFoo(<className> &data, int first, int last)
{
int partitionIndex = -1;
data[first]=true;
data[last]=true;
for (int i = first + 1; i < last; i++)
{
//some logic setting the index
If ( some condition is true)
partitionIndex = i;
}
//no dependency of partitions on one another and so can be parallelized
if( partitionIndex != -1)
{
data[partitionIndex]=true;
//assume some threadlimit
if (Commons::GetCurrentThreadCount() < Commons::GetThreadLimit())
{
std::thread t1(recursiveFoo, std::ref(data), first, index);
Commons::IncrementCurrentThreadCount();
recursiveFoo(data, partitionIndex , last);
t1.join();
}
else
{
nonRecursiveFoo(data, first, partitionIndex );
nonRecursiveFoo(data, partitionIndex , last);
}
}
}
//主要
int main()
{
recursiveFoo(data,0,data.size-1);
}
//共同点
std::mutex threadCountMutex;
static void Commons::IncrementCurrentThreadCount()
{
threadCountMutex.lock();
CurrentThreadCount++;
threadCountMutex.unlock();
}
static int GetCurrentThreadCount()
{
return CurrentThreadCount;
}
static void SetThreadLimit(int count)
{
ThreadLimit = count;
}
static int GetThreadLimit()
{
return ThreadLimit;
}
static int GetMinPointsPerThread()
{
return MinimumPointsPerThread;
}
【问题讨论】:
-
这段代码可以编译和工作吗?如果是这样,您应该尝试在 codereview 网站上发布此内容:codereview.stackexchange.com
-
你不应该依赖阅读线程看到更新到
CurrentThreadCount,当他们没有锁定他们的读取访问权限时;使用 atomic_int 会更好。无论如何,我建议您添加一些日志记录,以向您展示线程实际上是如何划分工作的。是否可以期望更快还取决于您正在处理的数据量:太少和线程创建的开销将使收益相形见绌。实际上,如果您的分区不能平均分配工作,您最终可能会得到一些运行时间很短的线程,而 1 或 2 最终会同步完成大部分工作。 -
仅仅因为你的代码线程化并不意味着它更快。在分析单线程代码方面做了什么?
-
这可能有多种原因,但首先: thd 程序 rougvmy 是如何运行 lonc 的?你有多少数据项?你有几个核心?你的线程数限制是多少?
-
你用什么编译器?
标签: c++ multithreading performance recursion parallel-processing