套接字发送并发保证

套接字发送并发保证

本文介绍了套接字发送并发保证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在两个进程(或两个线程)之间共享一个套接字,并且在这两个进程中,我都尝试发送一个阻塞的大消息(大于下划线协议缓冲区),是否可以保证两个消息都将顺序发送?还是消息可以在内核中交错?

If I have a single socket shared between two processes (or two threads), and in both of them I try to send a big message (bigger than the underlining protocol buffer) that blocks, is it guaranteed that both messages will be sent sequentially? Or it possible for the messages to be interleaved inside the kernel?

我主要对基于IP的TCP行为感兴趣,但是了解它是否根据套接字的协议而变化将很有趣.

I am mainly interested in TCP over IP behavior, but it would be interesting to know if it varies according to socket's protocol.

推荐答案

您要问,如果您write()消息A,然后B在同一套接字上,那么A是否一定会在B之前到达?对于SOCK_STREAM(例如TCP)和SOCK_SEQPACKET(几乎从未使用)套接字,答案是不合格的是.对于Internet上的SOCK_DGRAM(即UDP数据包),答案是否定的:数据包可以由网络重新排序.在单个主机上,unix域数据报套接字将(在我所知道的所有系统上)保留顺序,但是我不相信任何标准都可以保证这种顺序,而且我敢肯定会出现边缘情况.

You're asking that if you write() message A, then B on the same socket, is A guaranteed to arrive before B? For SOCK_STREAM (e.g. TCP) and SOCK_SEQPACKET (almost never used) sockets, the answer is an unqualified yes. For SOCK_DGRAM over the internet (i.e. UDP packets) the answer is no: packets can be reordered by the network. On a single host, a unix domain datagram socket will (on all systems I know) preserve ordering, but I don't believe that's guaranteed by any standard and I'm sure there are edge cases.

还是等待:也许您是在问两个进程编写的消息是否混合在一起?是的:单个系统调用(write/writev/sendto/sendmsg)始终将其内容原子地放入文件描述符中.但是显然,如果您或您的库将写入拆分为多个调用,则会失去保证.

Or wait: maybe you're asking if the messages written by the two processes won't be mixed? Yes: single system calls (write/writev/sendto/sendmsg) always place their content into a file descriptor atomically. But obviously if you or your library splits that write into multiple calls, you lose that guarantee.

这篇关于套接字发送并发保证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 14:25