简体   繁体   English

在来自多个线程的阻塞套接字上使用send()

[英]Using send() on a blocking socket from multiple threads

I have read that you are not supposed to use send() on a blocking socket from multiple threads, but I do not know why! 我读过您不应该在来自多个线程的阻塞套接字上使用send() ,但是我不知道为什么! And if I want to use send() from multiple threads, is there anything I can do to allow it? 如果我想从多个线程中使用send() ,是否可以做些允许的事情?

I am using Windows. 我正在使用Windows。

The fundamental reason is that synchronous I/O functions use the handle object (sockets are implemented as handles) to keep track of whether the I/O is complete or not. 根本原因是同步I / O函数使用handle对象(将套接字实现为handle)来跟踪I / O是否完成。

The result is that if you try to send() to the same socket from multiple threads simultaneously, send() is liable to (a) hang or (b) exit before the I/O is actually complete, with catastrophic results. 结果是,如果您尝试同时从多个线程向同一套接字发送send(),则send()可能会(a)挂起或(b)在I / O实际完成之前退出,从而导致灾难性的结果。

You can use a critical section to prevent the sends from overlapping, or have a designated thread that reads data to send from a queue. 您可以使用关键部分来防止发送重叠,或​​者使用指定的线程来读取要从队列发送的数据。

Note that this only applies if the sends are to the same socket. 请注意,这仅在发送到同一套接字的情况下适用。 Sending to different sockets simultaneously is fine. 同时发送到不同的套接字很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM