Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call recv() on the same blocking socket from two threads

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?

like image 521
Claudiu Avatar asked Mar 18 '09 22:03

Claudiu


People also ask

Is recv () a blocking call?

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.

Is RECV a blocking call in C?

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.

What does recv () return?

If successful, recv() returns the length of the message or datagram in bytes. The value 0 indicates the connection is closed.

Why is recv blocking?

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.


2 Answers

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?

like image 185
dwc Avatar answered Nov 06 '22 04:11

dwc


Socket implementations should be thread-safe, so exactly one thread should get the data when it becomes available. The other call should just block.

like image 38
Antti Huima Avatar answered Nov 06 '22 06:11

Antti Huima