Is it safe to issue blocking write() calls on the same TCP socket from multiple threads?

后端 未结 1 1139
深忆病人
深忆病人 2020-12-28 20:47

Let\'s say I have two threads, T1 and T2.

Thread T1 makes a blocking write() call on a TCP socket S to send a large buffer of bytes B1. The buffer of bytes B1 is so

相关标签:
1条回答
  • 2020-12-28 21:44

    It Tries

    TL;DR: for the purpose of writing and debugging code, it's safe to assume atomicity, unless your target is a life support system.


    It is always going to be bad if a send(2) (same as write(2)) on a tcp socket is not atomic. There is never a good reason to implement a non-atomic write. All versions of Unix and Windows attempt to keep the write atomic, but apparently very few provide a guarantee.

    Linux is known to "usually"1. get this right but it has a bug, even in recent kernels. It does attempt to lock the socket but under certain circumstances a memory allocation can fail and a write will be split up. See this IBM blog entry on sendmsg for details. [Link fixed.]

    According to those tests, only AIX and Solaris completely passed a thread-stress-test. It is not known if even those systems have failure cases that simply were not uncovered.


    1. TL;DR: Almost always, i.e., always except in the presence of a certain error.

    0 讨论(0)
提交回复
热议问题