Based on this article, calling WSASend()
or WSARecv()
from multiple threads is not safe. However, is it safe to call WSASend()
and WSARecv()
at the same time from two threads?
Asked
Active
Viewed 1,110 times
4
-
What? Does "two threads" not qualify as "multiple threads" to you? – Jonathon Reinhart Feb 27 '15 at 17:25
-
1I'm assuming that the wording of the question can be improved and what is being asked is this... "Can I call `WSASend()` from one thread and `WSARecv()` from another thread simultaneously on the same socket without causing problems as highlighted in the referenced article..." If that IS the question then effectively you're asking if you could protect each 'side' of the connection with a separate lock rather than using a single lock around both sends and receives. – Len Holgate Feb 27 '15 at 17:30
-
It is certainly safe insofar as it will not crash and insofar as send and receive buffers are separate entities. One thread sending and one thread receiving therefore doesn't hurt. What isn't safe is having two (or more) threads send concurrently or receive concurrently. Although this, too, is "safe" - it won't crash or such... it's just that they'll be writing to the buffer (or removing data from the buffer) at the same time in an unspecified order, which almost certainly won't give consistent, meaningful results. Note that e.g. `printf` is just as "unsafe" in that respect. – Damon Feb 27 '15 at 17:56
-
1@Len Holgate This is exactly what I meant :-) – Feb 27 '15 at 19:22
1 Answers
4
It is always safe to read from a socket in one thread while simultaneously writing to the same socket in another thread. Separate kernel buffers are involved. Regardless of whether you are using blocking, non-blocking, overlapped, or IOCP I/O logic.
What is not safe is simultaneously reading from the same socket in multiple threads, or simultaneously writing to the same socket in multiple threads. That requires synchronization between the threads so their transmitted/received data do not overlap each other.

Remy Lebeau
- 555,201
- 31
- 458
- 770
-
This is only partially correct. It is thread-safe, it just doesn't respect ordering. It's pretty common to have concurrent send/recv on UDP socket, for instance, where ordering doesn't matter. – Cory Nelson Feb 27 '15 at 21:36
-
3Concurrent send+recv is fine. Concurrent recv+recv, and concurrent send+send, is not fine. I never said anything about thread-safe. That is a whole other issue. – Remy Lebeau Feb 27 '15 at 21:39