Reading/Writing sockets concurrently
simonmar at microsoft.com
Fri Dec 10 05:51:38 EST 2004
On 09 December 2004 17:46, Mårten Dolk wrote:
> I'm trying to create a client application that needs to read and write
> data from a socket. What I want to do is to have one thread reading
> the socket and another thread writing to the same socket, but I can't
> get it to work.
> I know that there is a problem with having two threads reading from
> the same Handle (as in the aaaa bbbb example), due to the locking. To
> avoid this blocking I open the socket with Network.Socket.socket and
> create two handles with socketToHandle, one in ReadMode and one in
Actually you don't need to create two Handles to a socket - the socket Handle is a "duplex" Handle with two locks, so the read and write sides don't interfere with each other.
In fact, you shouldn't create two Handles to the same socket, because as soon as one of the finalizers runs it will close the socket.
> But the threads still seem to be blocking each other and the program
> runs very slowly. I am using channels to have the read and write
> threads communicate with other threads in the application and by
> removing a writeChan in one of these other threads the program
> crashes with a "Fail: thread blocked indefinitely".
Looks like a deadlock of some kind. Compiling with -debug and running with +RTS -Ds might give you some clues.
More information about the Glasgow-haskell-users