Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I attach a TChan mailbox to a thread and receive/send messages using sockets?

Tags:

haskell

I want to manually create TChan mailboxes for threads where messages/network packets that come in get collected in the same queue as messages from local threads.

I am not sure what a typical Haskell approach would be here. How can I write from e.g. a socket to a TChan mailbox?

Will it then be one Mailbox with several separate queues? Or in deed several mailboxes?

I have looked into epass but not tried yet. Altough I think what I want to do should be possible I have not really a detailed idea to get me started. Does anyone have a code example of something similar?

like image 629
J Fritsch Avatar asked Oct 10 '22 06:10

J Fritsch


1 Answers

I suspect you may be overthinking this a bit, actually. TChan is a pretty simple abstraction, and merely an inert data structure on its own. If you want to use one, just have threads read/write using it as appropriate.

So to connect a socket, you can simply create code that polls the socket and writes anything there to the TChan. Put that in an infinite loop then wind it up and let it fly. Haskell's threads are pretty darn lightweight and immutability means concurrency headaches mostly don't exist, so other than being careful not to use blocking FFI calls (this could be a concern with sockets, so read the documentation) there's no reason to hesitate to use threads when they make sense.

If you really do want something fancier than that and find a library that would work, perhaps epass, then what you really want is example code for that specific library.

Oh, and for what it's worth--the implementation of TChan is essentially a linked list made of TVars with two references into it, nothing more. Reading moves the head pointer forward, leaving the earlier cells alone for either copies of the TChan or the garbage collector to find, and writing creates a new cell at the tail pointer. All of that is done in STM transactions, of course.

like image 188
C. A. McCann Avatar answered Oct 13 '22 12:10

C. A. McCann