3

一、D如何创建并行foreach(底层逻辑)?

int main(string[] args)
{
    int[] arr;
    arr.length = 100000000;
    /* Why it is working?, it's simple foreach which working with
       reference to int from arr, parallel function return ParallelForeach!R
       (ParallelForeach!int[]), but I don't know what it is.
       Parallel function is part od phobos library, not D builtin function, then what
       kind of magic is used for this? */
    foreach (ref e;parallel(arr))
    {
        e = 100;
    }
    foreach (ref e;parallel(arr))
    {
        e *= e;
    }
    return 0;
}

其次,为什么它比简单的 foreach 慢?最后,如果我创建自己的 taskPool(并且不使用全局 taskPool 对象),程序永远不会结束。为什么?

4

1 回答 1

5

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();
        }
    }
}

其中workUnitIndexshouldContinue是共享变量,并且dg是 foreach 委托

它较慢的原因仅仅是因为将函数传递给池中的线程并以原子方式访问共享变量所需的开销。

您的自定义池未关闭的原因可能是您没有关闭线程池finish

于 2014-05-16T16:28:23.517 回答