互斥和 C 套接字

发布于 2024-07-22 06:05:17 字数 181 浏览 5 评论 0原文

我正在维护一个现有的系统,以前的开发人员对每个操作都是在套接字上执行的,需要多个线程对其进行读写,以前的开发人员在控制和互斥体下执行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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

箹锭⒈辈孓 2024-07-29 06:05:17

默认情况下,套接字不是线程安全的。 因此,如果您有多个线程读取和写入它们,您将需要以某种方式锁定访问(例如使用互斥锁)。

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).

云柯 2024-07-29 06:05:17

对于 TCP(AF_INET、SOCK_STREAM),可以有一个不同步的读取线程(recv)和写入线程(send)。

但从您的描述来看,并不清楚您的代码中使用互斥体的目的 - 它看起来像“以前的开发人员”同步网络操作不是因为套接字,而是因为您的应用程序协议的要求。
许多应用程序以这种方式执行通信:

lock
-> send request
<- recv reply
unlock

lock
-> send request
<- recv reply
unlock

这里需要锁定(如果涉及多个线程)来同步发送/接收对,否则您的应用程序协议可能会变成一堆不匹配的请求和回复。

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:

lock
-> send request
<- recv reply
unlock

lock
-> send request
<- recv reply
unlock

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文