Possible to pass a member function to spawn?

Oliver Puerto saxo123 at gmx.de
Mon Feb 6 13:38:03 PST 2012


I'm very new to D. Just started reading "The D programming language". I should read it from beginning to end before posting questions here. I know ... But I'm just too impatient. The issue seems not to be that simple, nevertheless. The code below compiles with Visual Studio.

I want to have something like my actor class that I can start running in it's own thread like in Scala or other languages that support actors. So at best, I would like to do something like this:

    MyActor myActor = new MyActor();
    auto tid = spawn(&start, &myActor.run());

However, this doesn't work. So I came up with the solution below where the start function is called with myActor as an argument. The code at the end of the mail prints this to the console:

MyActor 123
Main thread received message: -1

This solution works, but is really not very elegant. I'm not sure whether declaring MyActor shared is a good solution. The minimum I would like to achieve is to have the start function in the source file with the MyActor class. Also this does not compile. I played with delegates but couldn't get it to compile.

I'd be thankful for any useful suggestions or hints.

Regards, Oliver Plow

-------------------- beginning of main.d -------------- 

import MyActor;

int main()

    MyActor myActor = new MyActor();
    auto tid = spawn(&start, myActor); 


       (int x) {
        writeln("Main thread received message: ", x);

    return 0;

void start(MyActor actor)
    bool cont = true;

    while (cont)
            (int msg) { actor.run(msg); },
            (Tid sender) { cont = false; sender.send(-1); },
	    (Variant v) { writeln("huh?"); } 

-------------------- end of main.d -------------- 

-------------------- beginning of MyActor.d -------------- 

shared class MyActor {

    void run(int i) {
        write("MyActor ");


-------------------- end of MyActor.d --------------

Empfehlen Sie GMX DSL Ihren Freunden und Bekannten und wir
belohnen Sie mit bis zu 50,- Euro! https://freundschaftswerbung.gmx.de

More information about the Digitalmars-d mailing list