在 Linux 中从共享相同文件描述符的多个线程写入同一个管道是线程安全的吗?

问题描述 投票:0回答:2

我有一个有两个线程的 Linux 进程,它们共享同一个文件描述符,每 100 毫秒将 400 字节的数据写入同一个管道。我想知道 POSIX 是否保证这是线程安全的,或者我是否需要添加额外的同步机制来序列化从多个线程(而不是进程)到管道的写入。

我还知道 POSIX 保证从不同进程向同一个管道多次写入小于 PIPE_BUF 字节的数据是原子写入的。但是我不确定相同的保证是否适用于同一进程中多个线程的写入。

任何人都可以对此提供一些见解吗?在 Linux 中使用相同的文件描述符从多个线程写入同一管道时,我应该使用任何其他同步机制来确保线程安全吗?

提前感谢您的任何帮助或建议!

multithreading pipe posix ipc embedded-linux
2个回答
0
投票

man 2 write
(Linux 手册页 6.02)说:

   According to POSIX.1-2008/SUSv4 Section XSI 2.9.7 ("Thread Interactions
   with Regular File Operations"):

       All of the following functions shall be atomic with respect to each
       other in the effects specified in POSIX.1-2008 when they operate on
       regular files or symbolic links: ...

   Among  the  APIs  subsequently  listed  are write() and writev(2).  And
   among the effects that should be atomic across threads (and  processes)
   are  updates  of the file offset.  However, before Linux 3.14, this was
   not the case: if two processes that share an open file description (see
   open(2))  perform  a  write() (or writev(2)) at the same time, then the
   I/O operations were not atomic with respect to updating the  file  off-
   set,  with  the  result  that the blocks of data output by the two pro-
   cesses might (incorrectly) overlap.  This problem was  fixed  in  Linux
   3.14.

因此,只要您至少运行 Linux 3.14(将近 9 岁),它就应该是安全的。


0
投票

posix标准中,关于一般信息我们读到:

2.9.1 线程安全

本卷 POSIX.1-2008 定义的所有函数都应是线程安全的,但以下函数不需要是线程安全的。

后面没有列出 read 和 write 。确实,从多个线程调用它们是安全的。然而,这仅意味着系统调用不会崩溃,它并没有说明并行调用它们的确切行为。特别是,它没有提到原子性。

但是在文档中关于

write
系统调用我们读到:

原子/非原子:如果一次操作中写入的全部量不与来自任何其他进程的数据交错,则写入是原子的。当有多个写入器向单个读取器发送数据时,这很有用。应用程序需要知道可以预期以原子方式执行多大的写入请求。这个最大值称为 {PIPE_BUF}。 POSIX.1-2008 卷没有说明超过 {PIPE_BUF} 字节的写请求是否是原子的,但要求 {PIPE_BUF} 或更少字节的写请求是原子的。

© www.soinside.com 2019 - 2024. All rights reserved.