views:

393

answers:

1

Hi, I'm using a C socket library I found online to implement a tcp socket data transfer program.

Is it possible to make 2 threads share the same socket connection (1 read and 1 write), and have the read thread perform a blocking read and recv data while the write thread constantly writes data?

All of the example socket programs I've seen only do 1 way communication, or send data only after it receives.

Thank you.

+2  A: 

I don't know of any technical reason why you can't do that. Whether it's advisable or not for your situation is another question. :)

The main situation in which you'd want to avoid this multi-threaded type of approach is if reads and writes are dependent on each other at the application level. I don't really know what you're doing with respect to handling the data, but the reader/writer approach can be difficult to unwind.

Seth
ok thanks, just wanted to make sure it's possible since i've never seen any examples of it
Actually my concern was: if u call a mutex around the socket read in the read thread, then how would the write thread access the socket.
Well, if you use a mutex to only allow one thread to access the socket at a time, then your 2 thread model won't work. Essentially, you'd have to let both threads access the socket's file descriptor.
Seth
But what happens if both threads call the read() and write() function from the socket class at the same time?
TCP sockets are full-duplex, so you're fine. Modern TCP sockets are capable of exactly what you need. http://en.wikipedia.org/wiki/Full_duplex#Full-duplex
Seth