互斥和 C 套接字
我正在维护一个现有的系统,以前的开发人员对每个操作都是在套接字上执行的,需要多个线程对其进行读写,以前的开发人员在控制和互斥体下执行io操作。 是否需要相互排除C套接字IO操作? 或者由于套接字是全双工的,因此互斥体的使用是多余的? 只有一个线程
在我看来,毫无疑问,线程放入对象的处理队列是共享内存,必须注意相互排斥。
I am maintaining an existing system where previous developers on each operation is performed on the socket, to which multiple threads are required to read and write to, the previous developers have performed the io operations under the control and a mutex. is there a requirement to mutually exclude C socket IO operations? Or since sockets are full duplex, the use of a mutex is redundant? Only one thread
There is no question in my mind that the processing queue to which the thread puts an object into is shared memory and care must be taken to mutually excluse it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认情况下,套接字不是线程安全的。 因此,如果您有多个线程读取和写入它们,您将需要以某种方式锁定访问(例如使用互斥锁)。
Sockets are not thread-safe by default. So if you have multiple threads reading and writing to them you will need to lock access in some way (e.g. with a mutex).
对于 TCP(AF_INET、SOCK_STREAM),可以有一个不同步的读取线程(recv)和写入线程(send)。
但从您的描述来看,并不清楚您的代码中使用互斥体的目的 - 它看起来像“以前的开发人员”同步网络操作不是因为套接字,而是因为您的应用程序协议的要求。
许多应用程序以这种方式执行通信:
这里需要锁定(如果涉及多个线程)来同步发送/接收对,否则您的应用程序协议可能会变成一堆不匹配的请求和回复。
in case of TCP (AF_INET, SOCK_STREAM) it is OK to have a reader thread (recv) and a writer thread (send) which are not synchronized.
But from your description it is not clear for what purpose mutex is used in your code - it looks like "previous developers" synchronized networking operations not because of sockets, but due to requirements of your application protocol.
Many applications perform communications this way:
locking is required here (if multiple threads are involved) to synchronize send/recv pairs, otherwise your application protocol might become a mess of unmatched requests and replies.