Possible to pass a member function to spawn?

saxo123 at gmx.de saxo123 at gmx.de
Thu Feb 9 00:29:54 PST 2012


Hello,

I'm the guy that made the initial post in this thread. Well, some 100 or so replies ago :-). I must admit that I cannot always follow the discussion as I'm a real D newbie. As I understand one issue discussed is that the actor class is declared shared (see blow the solution I meanwhile came up with). The "trick" I'm doing is the MyActor.start() thing: the created instance of MyActor is not returned to the outside world but only the tid of the spawned thread. This way nobody gets a reference to an actor object he could play with from within a different thread.

Problem is that this also compiles:

MyActor myActor = new MyActor();
auto tid = myActor.start();
myActor.run(i);	// call from the parent thread!

I believe I will just write down in the docs that this approach is strongly discouraged! Another problem ist that

auto tid = MyActor.start();

doesn't compile as it should: Error: undefined identifier module MyActor.start

This is a bit strange since this should be legal, f.x. p.176 in the book by Alexandrescu provides a analogous example. Same with "tid.send(thisTid, Actor.SHUTDOWN)" with Actor.SHUTDOWN.

Regards, Oliver


int main()
{

    auto tid = MyActor.start();

    tid.send(123);    
    tid.send(456);    
    tid.send(1.0f);

    tid.send("hello");

    tid.send(thisTid, Actor.SHUTDOWN);

    receive( 
        (int x) { writeln("spawned actor has shut down with return code: ", x); 
    });

    return 0;
}

----------------- Actor.d ------------------------

shared abstract class Actor {    

    public static string SHUTDOWN = "shutdown";

    protected bool cont = true;

    Tid start() {
        return spawn(&dispatch, this);
    }

    void run() {
        while(cont) {
            act();
        }
    }

    abstract void act();

    protected bool checkShutdown(Tid sender, string msg) {
        if(msg == SHUTDOWN) {
            writeln("shutting down ...");
            cont = false;
            sender.send(0);
            return true;
        }
        return false;
    }

}

void dispatch(Actor actor)
{
    actor.run();
}

----------------- End of Actor.d ------------------------


----------------- MyActor.d ------------------------

shared class MyActor : Actor {    

    void run(int i) {
        writeln(i);
    }

    void act() 
    {
        receive(
            (int msg) { run(msg); },
            (Tid sender, string msg) { checkShutdown(sender, msg); },
            (Variant v) { writeln("huh?"); }            
        );
    }

}
-- 
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