YGL
YGL

Reputation: 5570

tasks from member functions using std.parallelism in D

I would like to create a task that executes a member function of a struct or class:

import std.parallelism, std.stdio;

struct S {
    void foo() {
        writeln("S.foo()");
    }
}

void main() {
    S s;
    auto pool = new TaskPool();
    auto t = task!(s.foo)(); // error
    pool.put(t);
    pool.finish();
}

How can I achieve this? I also tried using delegates to no avail.


edit: I found a potentially related question here.

Upvotes: 1

Views: 157

Answers (1)

jA_cOp
jA_cOp

Reputation: 3305

import std.parallelism, std.stdio;

struct S {
    void foo() {
        writeln("S.foo()");
    }
}

void main() {
    S s;
    auto pool = new TaskPool();
    auto t = task(&s.foo); // Constructor taking a runtime function pointer, delegate or callable (opCall).
    pool.put(t);
    pool.finish();
}

Output:

S.foo()

You can use scopedTask as well, but then you have to wait until the task has finished before returning. TaskPool.finish does not wait.

Upvotes: 3

Related Questions