Reading/Writing sockets concurrently

Hi, 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 WriteMode. 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". Are there any good examples of how to use sockets with Haskell. I have no way of knowing in which order I will need to read data from and write data to the socket. I am using ghc version 6.2.2 on Linux. Thanks in advance -Mårten-

G'day all.
Quoting Mårten Dolk
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.
You could take a look at lambdabot: http://www.scannedinavian.org/repos/lambdabot/lambdabot/ It has a two-thread structure similar to what you appear to need. Look in IRC.hs specifically. Cheers, Andrew Bromage

Hi! Thanks for the reply! ajb@spamcop.net 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.
You could take a look at lambdabot:
http://www.scannedinavian.org/repos/lambdabot/lambdabot/
It has a two-thread structure similar to what you appear to need. Look in IRC.hs specifically.
That code looked very much like what I was trying to do. The difference? I had my writer loop running in the main thread. Forking the writer to its own thread did take care of the evil "Fail: thread blocked indefinitely". But I'm still not sure about the scheduling/blocking issue. You do seem to have one thread reading to the same handle as another thread is reading. Isn't that a problem? Well, the code works well enough for my purposes now. :) Btw, you import GHC.IO and not System.IO. What is the diffrence between those two? Thanks, Mårten
participants (2)
-
ajb@spamcop.net
-
Mårten Dolk