Threads and OwnerTerminated
Jonathan M Davis
jmdavisProg at gmx.com
Thu Nov 17 14:21:31 PST 2011
On Thursday, November 17, 2011 11:56 Andrej Mitrovic wrote:
> This is an example from TDPL:
>
> import std.concurrency;
> import std.exception;
> import std.stdio;
>
> void main()
> {
> auto low = 0;
> auto high = 100;
> auto tid = spawn(&writer);
>
> foreach (i; low .. high)
> {
> writeln("Main thread: ", i);
> tid.send(thisTid, i);
> enforce(receiveOnly!Tid() == tid);
> }
> }
>
> void writer()
> {
> for (;;)
> {
> auto msg = receiveOnly!(Tid, int)();
> writeln("Secondary thread: ", msg[1]);
> msg[0].send(thisTid);
> }
> }
>
> This will throw an OwnerTerminated exception on exit since the writer
> thread calls receiveOnly() after the main thread was killed:
> std.concurrency.OwnerTerminated at std\concurrency.d(214): Owner terminated
>
> So what is expected here, am I always supposed to wrap receive() in a
> try/catch?
I generally either use functions with std.concurrency which run once and
return or which run until they're sent a message telling them to terminate. In
either case, an OwnerTerminated exception would only occur if something went
wrong, so while you _can_ wrap the receive calls in try-catch blocks just in
case something goes wrong, it shouldn't be necessary in the general case.
> Btw, is std.concurrency planned to be expanded/improved upon? Or is
> this a low-level portable messaging API (emphasis on messaging,
> core.thread is lower-level), on top of which more complex APIs can be
> built on?
I believe that it's intended to be expanded on such that Tid does not
necessarily indicate a thread, but instead it could be used to communicate
with a socket so that you could use send and receive across the network. But I
believe that it's Sean Kelly who is dealing with that, and I don't know where
he stands with it (my guess would be that it's planned but with no real work
done on it yet given everything else that he has to do, but I don't know).
But that's the basic plan as I understand it.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list