POSIX: yes
2.9.1 Thread-Safety
All functions defined by this volume of POSIX.1-2008 shall be thread-safe, except that the following functions need not be thread-safe.
Source: https://pubs.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_09.html#tag_02_09_01
Windows: also yes
3.10 - Is Winsock thread-safe?
On modern Windows stacks, yes, it is, within limits.
It is safe, for instance, to have one thread calling
send()
and another thread callingrecv()
on a single socket.By contrast, it’s a bad idea for two threads to both be calling
send()
on a single socket. This is “thread-safe” in the limited sense that your program shouldn’t crash, and you certainly shouldn’t be able to crash the kernel, which is handling thesesend()
calls. The fact that it is “safe” doesn’t answer key questions about the actual effect of doing this. Which call’s data goes out first on the connection? Does it get interleaved somehow? Don’t do this.Instead of multiple threads accessing a single socket, you may want to consider setting up a pair of network I/O queues. Then, give one thread sole ownership of the socket: this thread sends data from one I/O queue and enqueues received data on the other. Then other threads can access the queues (with suitable synchronization).
Applications that use some kind of non-synchronous socket typically have some I/O queue already. Of particular interest in this case is overlapped I/O or I/O completion ports, because these I/O strategies are also thread-friendly. You can tell Winsock about several OVERLAPPED blocks, and Winsock will finish sending one before it moves on to the next. This means you can keep a chain of these OVERLAPPED blocks, each perhaps added to the chain by a different thread. Each thread can also call
WSASend()
on the block they added, making your main loop simpler.
Source: https://tangentsoft.com/wskfaq/intermediate.html#threadsafety
Source: https://cboard.cprogramming.com/c-programming/150774-parallel-threads-socket-send-recv.html
No comments:
Post a Comment