Reputation:
I need to repeatedly send and receive UDP datagrams to/from a socket. My idea was to spawn two threads, one responsible for sending and the other for receiving. The whole idea makes sense only if it is possible to one thread to wait on a blocking recv()
and the other executing send()
on the same socket at the same time.
I did some Googling and found this SO question: Are parallel calls to send/recv on the same socket valid? The accepted answer mentions that send()
and recv()
are thread-safe (whew…), but then proceeds with an alarming remark:
This doesn't necessarily mean that they'll be executed in parallel
Oops. Does this mean that if I implement my multithreaded idea, will I end up with the sending thread waiting for the receiving thread’s recv()
to return before it actually starts sending its data? Bad.
It is ambiguous whether this accepted answer refers to two parallel send()
’s only, or if the concern is real also for an attempt to parallely execute one send()
and one recv()
. Therefore:
Will a call to send()
and a call to recv()
on the same socket by two threads be executed parallely, or will one of these calls block until the other returns?
Upvotes: 10
Views: 5073
Reputation: 104579
Short answer: You should be ok to have separate threads for sending and receiving with the same socket handle.
A common scenario is a video conferencing application. You might want to have one thread recording from the microphone and sending audio out the udp port. Another thread receives packets on the same port and plays them back over the speakers.
If your protocol is more synchronous (i.e. request/response flow - in order to send, you first have to receive something first), then a single likely thread makes more sense from a design perspective.
Upvotes: 4