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 calling recv() 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 these send() 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.

--------------------------------------------------------------------------------------------------------------------------------------

Atomicity of sendmsg() family of functions

SystemAtomicity
AIX 5.2Yes
FreeBSD 6.1No
HP-UX B.11.23No
IRIX 6.5.27No
Linux 2.6.xNo
Mac OS X 10.4 TigerNo
Solaris 10Yes
Windows 2000/XPYes, but with caveats

http://www.almaden.ibm.com/cs/people/marksmith/sendmsg.html

http://tangentsoft.net/wskfaq/intermediate.html#threadsafety 

转载于:https://www.cnblogs.com/slime/archive/2010/09/07/1820243.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值