Search code examples
socketshaskellhandle

Non-blocking close of Haskell Handle


We have two threads writing to a Handle wrapping a Socket. The Handle is useful because the MVar around it ensures that only one thread can be writing to it at once.

We require that one of the threads should be able to close the Handle, even if the other thread is in the middle of writing to it – the call to write should receive an error. The problem is that the hclose function blocks until it has exclusive access. What is the best way of working around this issue?


Solution

  • IIRC writing to handle locks the Handle, so you have two options: abort the operation using asynchronous exception or make it nonblocking (e.g. use hPutBufNonBlocking to try write and threadWaitWrite to wait for data to be sent).