www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Message passing pattern matching

reply "Casper =?UTF-8?B?RsOmcmdlbWFuZCI=?= <shorttail hotmail.com> writes:
Hey, I'm handling concurrency with message passing, previously 
with D's concurrency, now with Vibe-d, which I assume works the 
same way.

My app is a chat server, and when a connection is opened to a 
client, I store the Tid of the thread (or fibre?) handling 
sending messages out to the client. This lets me broadcast 
messages to all Tids. When a connection is closed, the thread 
requests that its Tid is removed from the list.

Both adding and removing the Tid technically require only the Tid 
to be message passed. However, I would like to distinguish 
between the two cases. I currently have two empty structs named 
AddTid and RemoveTid, and I pass those along. I assume some bytes 
must be passed in their place to tell of their type, but that's 
fine.

It does feel rather hacked, however. I'm aware that D doesn't 
support excessively fancy pattern matching, like what is found in 
SML, but is there a more correct way to do this? Enums don't 
work, because they have the same type. I can pattern match the 
enums later, but I want to do it immediately.
Jan 29 2014
parent reply "Casper =?UTF-8?B?RsOmcmdlbWFuZCI=?= <shorttail hotmail.com> writes:
A small example:

while (true) {
   receive(
     (Tid tid, AddTid _) {some code}
     (Tid tid, RemoveTid _) {some other code}
     (string s) {broadcast stuff}
   )
}

struct AddTid {}
struct RemoveTid {}
Jan 29 2014
parent "Stanislav Blinov" <stanislav.blinov gmail.com> writes:
On Wednesday, 29 January 2014 at 21:50:28 UTC, Casper Færgemand 
wrote:
 A small example:

 while (true) {
   receive(
     (Tid tid, AddTid _) {some code}
     (Tid tid, RemoveTid _) {some other code}
     (string s) {broadcast stuff}
   )
 }

 struct AddTid {}
 struct RemoveTid {}
From where I sit that's a perfectly fine approach. After all, you do want to distinguish your own message types: any other std.concurrency-aware code (i.e. library) could pass its own messages. You wouldn't want to mistake those for your own private communication protocol.
Jan 29 2014