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

Jay picture Jay · Dec 30, 2009 · Viewed 56.8k times · Source
  1. Can we call send from one thread and recv from another on the same socket?
  2. Can we call multiple sends parallely from different threads on the same socket?

I know that a good design should avoid this, but I am not clear how these system APIs will behave. I am unable to find a good documentation also for the same.

Any pointers in the direction will be helpful.

Answer

Chris Dodd picture Chris Dodd · Dec 30, 2009

POSIX defines send/recv as atomic operations, so assuming you're talking about POSIX send/recv then yes, you can call them simultaneously from multiple threads and things will work.

This doesn't necessarily mean that they'll be executed in parallel -- in the case of multiple sends, the second will likely block until the first completes. You probably won't notice this much, as a send completes once its put its data into the socket buffer.

If you're using SOCK_STREAM sockets, trying to do things a parallel is less likely to be useful as send/recv might send or receive only part of a message, which means things could get split up.

Blocking send/recv on SOCK_STREAM sockets only block until they send or recv at least 1 byte, so the difference between blocking and non-blocking is not useful.