此声明来自Programming Rust, 2nd Edition这本书让我有点困惑,
... the Rust standard library protects
stdin
with a mutex. (Without a mutex two threads trying to read fromstdin
at the same time would cause undefined behavior. C has the same issue and solves it the same way: all of the C standard input and output functions obtain a lock behind the scenes. The only difference is that in Rust, the lock is part of the API.)
如果 C 中的两个线程使用 stdio.h
幕后是否有任何“互斥体”来处理文件句柄上的争用?我一直认为这是你必须在 C 中明确做的事情,而不是别人为你做的事情。此外,如果您编译单线程 C 应用程序,这些 stdio 的行为是否会神奇地改变并优化掉互斥体?
最佳答案
有互斥锁吗?
If two threads in C use stdio.h is there any "mutex" behind the scenes that handles contentions on the filehandle?
C 2018 7.21 7 说:
Each stream has an associated lock that is used to prevent data races when multiple threads of execution access a stream, and to restrict the interleaving of stream operations performed by multiple threads. Only one thread may hold this lock at a time. The lock is reentrant: a single thread may hold the lock multiple times at a given time.
单线程应用程序没有互斥体吗?
Moreover, if you compile a single-threaded C application, does the behavior of these stdio magically change and optimize away the mutex?
C 标准允许 C 实现执行此操作,因为 5.1.2.3 6 表示 C 实现只需产生按标准中指定的行为产生的可观察行为,而不是它必须以标准中描述的方式实现计划。我不知道是否有任何 C 实现可以做到这一点。由于模块使用 <stdio.h>
可以与创建线程然后调用以前的模块的模块分开编译,除非用户请求(可能通过命令行开关或 #pragma
指令),否则无法在编译时进行此选择。它必须在链接时(可能通过链接标准库的单线程版本)或运行时(可能在生成线程之前不使用任何锁)完成。
关于c - C 是否在幕后使用互斥锁处理 STDIN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68614127/