gpt4 book ai didi

c - 阅读;线程安全与否?

转载 作者:太空狗 更新时间:2023-10-29 17:24:35 25 4
gpt4 key购买 nike

同时从 2 个或更多不同线程对同一个文件描述符使用 pread 是否有问题?

最佳答案

pread 本身是线程安全的,因为它不在 list of unsafe functions 上.所以调用它是安全的。

真正的问题是:如果您同时读取同一个文件(不一定是两个线程,也可以是两个进程)会发生什么情况。

关于此,specification说:

  • The behavior of multiple concurrent reads on the same pipe, FIFO, or terminal device is unspecified.

    请注意,它没有提到普通文件。无论如何,该位仅与 read 相关,因为 pread 不能用于不可搜索的文件。

  • I/O is intended to be atomic to ordinary files and pipes and FIFOs.

    但这是来自非规范部分,因此您的操作系统可能会有所不同。例如,如果您从两个线程读取并且有一个并发写入,您可能会在两个读取缓冲区中获得不同的写入部分。但是这种问题并不是多线程特有的。

也很高兴知道在某些情况下

read() shall block the calling thread

不是进程,只是线程。和

A thread that has blocked shall not prevent any unblocked thread [...] from eventually making forward progress

关于c - 阅读;线程安全与否?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5155695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com