在同一套接字上并行调用 send/recv 是否有效? [英] Are parallel calls to send/recv on the same socket valid?

查看:32
本文介绍了在同一套接字上并行调用 send/recv 是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我们可以在同一个套接字上从一个线程调用 send 并从另一个线程调用 recv 吗?
  2. 我们可以从同一个套接字上的不同线程并行调用多个发送吗?

我知道好的设计应该避免这种情况,但我不清楚这些系统 API 的行为方式.我也找不到同样好的文档.

I know that a good design should avoid this, but I am not clear how these system APIs will behave. I am unable to find a good documentation also for the same.

任何有关方向的指示都会有所帮助.

Any pointers in the direction will be helpful.

推荐答案

POSIX 将 send/recv 定义为原子操作,所以假设你在谈论 POSIX send/recv 那么是的,你可以从多个线程和事物同时调用它们会工作.

POSIX defines send/recv as atomic operations, so assuming you're talking about POSIX send/recv then yes, you can call them simultaneously from multiple threads and things will work.

这并不一定意味着它们会并行执行——在多次发送的情况下,第二个可能会阻塞,直到第一个完成.您可能不会注意到这么多,因为一旦将数据放入套接字缓冲区,发送就完成了.

This doesn't necessarily mean that they'll be executed in parallel -- in the case of multiple sends, the second will likely block until the first completes. You probably won't notice this much, as a send completes once its put its data into the socket buffer.

如果您使用 SOCK_STREAM 套接字,那么尝试并行处理的可能性较小,因为 send/recv 可能仅发送或接收消息的一部分,这意味着事情可能会分裂.

If you're using SOCK_STREAM sockets, trying to do things a parallel is less likely to be useful as send/recv might send or receive only part of a message, which means things could get split up.

在 SOCK_STREAM 套接字上阻塞发送/接收只会阻塞直到它们发送或接收至少 1 个字节,因此阻塞和非阻塞之间的区别没有用.

Blocking send/recv on SOCK_STREAM sockets only block until they send or recv at least 1 byte, so the difference between blocking and non-blocking is not useful.

这篇关于在同一套接字上并行调用 send/recv 是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆