AFAIK TChan acts as a hub, every message sent is seen by others right ?!
i want a TChan that acts as a switch to send a message to specific thread, and also support broadcasting.
is there such thing ?
AFAIK TChan acts as a hub, every message sent is seen by others right
Share
Edit: I re-read your question. This answer doesn’t quite address “selective send”, though it clarifies what a
TChancan do.The “broadcast” approach described below will wake up all listeners (though on the bright side, it won’t make 1000 copies of each item). To avoid this, use the
Mapapproach as @Mikhail suggested. I did this in my chat server example.A
TChanis a FIFO queue:writeTChanadds an item to the end.readTChanreads an item from the beginning.For example, the following example forks 10 threads which fight over a single channel:
Here, each item is read by exactly one thread.
In contrast, the following example “broadcasts” a stream of items to 10 threads, by making ten copies of the channel using dupTChan:
Now each thread gets all of the items written to the channel.
A couple subtleties to note:
Items written to a channel prior to
dupTChanwill not appear in the new channel. If we calleddupTChanfrom the child threads rather than the main thread, somewriteTChans could happen first, meaning the children might not see all the items.Since nobody is reading the
masterchannel, items written to it will pile up and will likely not be garbage collected. To avoid this caveat, use newBroadcastTChan to create themasterchannel.