12

Possible Duplicate:
Are parallel calls to send/recv on the same socket valid?

I'm going to use one thread to receive data from socket(read) and another one to send data throughout socket(write).

Is it good idea to use one socket in two different threads?

Community
  • 1
  • 1
Dejwi
  • 4,393
  • 12
  • 45
  • 74
  • what platform(s) will this be running on? Some OSes take more kindly to such activities than do others – warren Sep 14 '11 at 14:50
  • Can someone clarify if this is the case on windows? I painfully found out that this is not the case for NamedPipes. There is just one lock on the file handle. So a read would block every write. I had to open another pipe to get my program work. – Lothar Nov 12 '15 at 19:28
  • In one video I have seen, the guy even said you should ALWAYS be reading and writing to the socket. Certainly you cannot interrupt reading to give something like a response. – The Fool May 07 '21 at 12:37

2 Answers2

20

There should be no problems sharing a socket across threads. If there is any kind of coordination required between the reading and the writing, and there probably will be, you're going to need to synchronize that in some way.

This article, File Descriptors And Multithreaded Programs, may be helpful and addresses the comment below.

... the socket library used for this should be threadsafe to start with and support a read from a socket in one thread and a write to the socket in the other ... The raw system calls read() and write() support this

From the socket manpage

Sockets of type SOCK_STREAM are full-duplex byte streams

You should be able to read and write both directions no problem, the directions are just about unrelated once the connection has been set up, at least in TCP.

Paul Rubel
  • 26,632
  • 7
  • 60
  • 80
  • 6
    While everything you say is true, I believe it doesn't fully answer the OP's question: is it possible to call `write` and `read` **at the same time** on the same socket ? – ereOn Sep 14 '11 at 14:39
  • 3
    Yes, one thread can read from the socket at the same time that another thread is writing to it. Just don't have multiple threads reading at the same time, or writing at the same time. – Remy Lebeau Sep 14 '11 at 19:57
5

Yes this should be fine. It is common to have one thread waiting to read the socket and other threads sending independently. The only thing you may need to be careful about is that two threads aren't writing at the same time.

DanS
  • 1,677
  • 20
  • 30