www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Is this a bug in the concurrency lib or am i using it incorrectly?

reply "Gary Willoughby" <dev kalekold.net> writes:
I was hoping the below example would display 'hello world' but it 
only displays 'hello'. Is this a bug in the concurrency lib or am 
i using it incorrectly?

import std.stdio;
import std.concurrency;

void writer()
{
	try
	{
		while (true)
		{
			receive((string s){
				writefln(s);
			});
		}
	}
	catch (OwnerTerminated ex)
	{
		// die.
	}
}

void sender(Tid writer)
{
	send(writer, "world");
}

void main(string[] args)
{
	auto writer = spawn(&writer);
	send(writer, "hello");
	spawn(&sender, writer);
}
Jul 01 2013
parent reply David <d dav1d.de> writes:
     try
     {
         while (true)
         {
             receive((string s){
                 writefln(s);
             });
         }
     }
     catch (OwnerTerminated ex)
     {
         // die.
     }
If you remove the the try..catch you will notice that OwnerTerminated is thrown, if this is the intended behaviour, I don't know. Probably is, because this would be a pretty obvious bug.
Jul 01 2013
parent reply "Gary Willoughby" <dev kalekold.net> writes:
 If you remove the the try..catch you will notice that 
 OwnerTerminated is
 thrown, if this is the intended behaviour, I don't know. 
 Probably is,
 because this would be a pretty obvious bug.
Ah right, so i guess the main thread is finishing and throwing the exception to writer before sender has sent anything?
Jul 01 2013
parent "John Colvin" <john.loughran.colvin gmail.com> writes:
On Monday, 1 July 2013 at 19:15:45 UTC, Gary Willoughby wrote:
 If you remove the the try..catch you will notice that 
 OwnerTerminated is
 thrown, if this is the intended behaviour, I don't know. 
 Probably is,
 because this would be a pretty obvious bug.
Ah right, so i guess the main thread is finishing and throwing the exception to writer before sender has sent anything?
An easy way of dealing with this would be to have main wait for a message from another thread telling it to terminate. My way of imagining threads in the std.concurrency model (for some reason it helps me not forget about these problems): It's a tree structure, where main is the master node and all other threads are - directly or indirectly - owned by main (main is owned by the OS) OS | main / | \ gravity 0 1 2 || / \ | \ || 3 4 5 6 || / \ \/ 7 8 If any thread lets go of it's parent for any reason, all the children below it fall to their deaths. Hmm...Concurrency Tree Diagrams. Is this already a thing? With some coloured arrows showing message pathways it could be a really nice visualisation of a complex multi-threaded program.
Jul 01 2013