Thread overview
Message passing pattern matching
Jan 29, 2014
Casper Færgemand
Jan 29, 2014
Casper Færgemand
Jan 29, 2014
Stanislav Blinov
January 29, 2014
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.
January 29, 2014
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 {}
January 29, 2014
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.