Are UNIX SOCK_DGRAM sockets thread-safe for recv() method?
If multiple threads are calling recv() on socket, are both guaranteed to get one clean UDP packet each or is there a chance of data getting mixed up?
Will the behavior be affected by whether socket is in blocking or non-blocking mode? Any pointers to documentation would be highly appreciated.
Calling recv()
from multiple threads is a safe operation. If the socket is a datagram socket then each recv returns a unique datagram that is not mixed up with other datagrams.
Posix standard explicitly enumerates all standard functions that are unsafe:
2.9.1 Thread-Safety
All functions defined by this volume of POSIX.1-2017 shall be thread-safe, except that the following functions1 need not be thread-safe.
asctime() basename() catgets() crypt() ctime() ....
There are almost 100 unsafe functions and further functions that are safe under certain conditions only. recv()
is not there. See POSIX.1-2017 2.9.1 Thread-Safety.