Parallel Iterators in the D language

只谈情不闲聊 提交于 2020-01-02 11:43:28

问题


I am trying to implement a graph data structure in the D language which supports parallel iteration over the node and edge sets.

alias ulong index;
alias index node;
alias ulong count;

class Graph {
    index z;    // max node index
    count n;    // number of nodes
    count m;    // number of edges
    node[][] adja;  // adjacency list
    count[] deg;    // node degree

    this(count n = 0) {
        this.z = n;
        this.n = n;
        this.m = 0;
        this.adja = new node[][](this.z, 0);
        this.deg = new count[](this.z);
    }

Here's a sequential node iterator method:

/**
 * Iterate over all nodes of the graph and call handler (lambda closure).
 */
void forNodes(F)(F handle) {
    foreach (node v; 0 .. z) {
        // call here
        handle(v);
    }
}

Works like this, and seems to work fine:

ulong sum1 = 0;
G.forNodes((node v) {
    sum1 += v;
});

Now I try a parallel version using the 'std.parallelism' module:

void parallelForNodes(F)(F handle) {
    foreach (node v; taskPool.parallel(z)) {
        // call here
        handle(v);
    }
}

But this gives me the a compiler error. What am I doing wrong here?

cls ~/workspace/Prototypes/PLPd $ ./main.d
/usr/local/Cellar/dmd/2.063/src/phobos/std/parallelism.d(3795): Error: cannot have parameter of type void
/usr/local/Cellar/dmd/2.063/src/phobos/std/parallelism.d(3796): Error: cannot have parameter of type void
/usr/local/Cellar/dmd/2.063/src/phobos/std/parallelism.d(1539): Error: template instance std.parallelism.ParallelForeach!(ulong) error instantiating
Graph.d(90):        instantiated from here: parallel!(ulong)
./main.d(100):        instantiated from here: parallelForNodes!(void delegate(ulong v) nothrow @safe)
Graph.d(90): Error: template instance std.parallelism.TaskPool.parallel!(ulong) error instantiating
./main.d(100):        instantiated from here: parallelForNodes!(void delegate(ulong v) nothrow @safe)
./main.d(100): Error: template instance Graph.Graph.parallelForNodes!(void delegate(ulong v) nothrow @safe) error instantiating
Failed: 'dmd' '-v' '-o-' './main.d' '-I.'

回答1:


parallel takes a range. Use std.range.iota to get the range equivalent of 0 .. z: foreach (v; parallel(iota(z))) {...}



来源:https://stackoverflow.com/questions/17837098/parallel-iterators-in-the-d-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!