D并联回路
首先,如何创建并行foreach(底层逻辑) 第二,为什么它比简单foreach慢? 最后,若我创建自己的taskPool(并且不使用全局taskPool对象),那个么程序永远不会结束。为什么?parallel返回一个结构(类型为D并联回路,d,phobos,D,Phobos,首先,如何创建并行foreach(底层逻辑) 第二,为什么它比简单foreach慢? 最后,若我创建自己的taskPool(并且不使用全局taskPool对象),那个么程序永远不会结束。为什么?parallel返回一个结构(类型为ParallelForeach),该结构实现了opApply(int delegate(…)foreach重载 调用时,结构将向私有submitAndExecute提交一个并行函数,该函数将同一任务提交给池中的所有线程 这就是: scope(failure) {
ParallelForeach
),该结构实现了opApply(int delegate(…)
foreach重载
调用时,结构将向私有submitAndExecute
提交一个并行函数,该函数将同一任务提交给池中的所有线程
这就是:
scope(failure)
{
// If an exception is thrown, all threads should bail.
atomicStore(shouldContinue, false);
}
while (atomicLoad(shouldContinue))
{
immutable myUnitIndex = atomicOp!"+="(workUnitIndex, 1);
immutable start = workUnitSize * myUnitIndex;
if(start >= len)
{
atomicStore(shouldContinue, false);
break;
}
immutable end = min(len, start + workUnitSize);
foreach(i; start..end)
{
static if(withIndex)
{
if(dg(i, range[i])) foreachErr();
}
else
{
if(dg(range[i])) foreachErr();
}
}
}
其中,workUnitIndex
和shouldContinue
是共享变量,dg
是每个代理的
其速度较慢的原因很简单,因为将函数传递给池中的线程和以原子方式访问共享变量所需的开销
您的自定义池没有关闭的原因可能是您没有使用关闭线程池,谢谢您的回答。我还有一个问题。我如何使用(在我的课堂上超载)opApply?在文档中没有描述应用操作符重载。请看,谢谢,这对我帮助很大。
scope(failure)
{
// If an exception is thrown, all threads should bail.
atomicStore(shouldContinue, false);
}
while (atomicLoad(shouldContinue))
{
immutable myUnitIndex = atomicOp!"+="(workUnitIndex, 1);
immutable start = workUnitSize * myUnitIndex;
if(start >= len)
{
atomicStore(shouldContinue, false);
break;
}
immutable end = min(len, start + workUnitSize);
foreach(i; start..end)
{
static if(withIndex)
{
if(dg(i, range[i])) foreachErr();
}
else
{
if(dg(range[i])) foreachErr();
}
}
}