[Haskell-cafe] How to make asynchronous I/O composable and safe?

Bardur Arantsson spam at scientician.net
Sat Jan 14 07:29:11 CET 2012

On 01/14/2012 06:24 AM, Joey Adams wrote:
> I'm not happy with asynchronous I/O in Haskell.  It's hard to reason
> about, and doesn't compose well.  At least in my code.

Async I/O *is* tricky if you're expecting threads to do their own 
writes/reads directly to/from sockets. I find that using a 
message-passing approach for communication makes this much easier.

If you need multiple server threads to respond to the same client 
(socket) then the easiest approach might be to simply use a (Chan a) for 
output. Since you always put full messages to the Chan, exceptions cause 
no problems with respect to partial messages, etc.

You can also use a Chan for forwarding messages from the client socket 
to the appropriate server threads -- if you need several (or even all) 
threads to receive messages from the client you can use "dupChan" on the 
"input-from-client" channel you pass to the server threads.

So, the API becomes something like:

    runSocketServer :: ((Chan a, Chan b) -> IO ()) -> ... -> IO ()

where the first parameter contains the "client logic" and "A" is the 
type of the messages from the client and "B" is the type of the messages 
which are sent back to the client.

Hope this helps,

More information about the Haskell-Cafe mailing list