What happens if I have one socket, s
, there is no data currently available on it, it is a blocking socket, and I call recv
on it from two threads at once? Will one of the threads get the data? Will both get it? Will the 2nd call to recv
return with an error?
recv(IPC, Buffer, int n) is a blocking call, that is, if data is available it writes it to the buffer and immediately returns true, and if no data is available it waits for at least n seconds to receive any data.
The recv() call blocks until data arrives on the socket. While it is blocked, other threads that are waiting for the lock are also blocked. Although this example is specific to network I/O, the recv() call could be replaced with any blocking call, and the same behavior would occur.
If successful, recv() returns the length of the message or datagram in bytes. The value 0 indicates the connection is closed.
recv will block until the entire buffer is filled, or the socket is closed. If you want to read length bytes and return, then you must only pass to recv a buffer of size length . This can avoid recv from blocking.
One thread will get it, and there's no way to tell which.
This doesn't seem like a reasonable design. Is there a reason why you need two threads calling recv()
on the same socket?
Socket implementations should be thread-safe, so exactly one thread should get the data when it becomes available. The other call should just block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With