c - C 是否在幕后使用互斥锁处理 STDIN?

标签 c multithreading input io mutex

此声明来自Programming Rust, 2nd Edition这本书让我有点困惑,

... the Rust standard library protects stdin with a mutex. (Without a mutex two threads trying to read from stdin 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/

相关文章:

c - 错误 C3861 : 'ls_file' : identifier not found

c++ - 为什么 i += a[i]++ 在使用 Visual C++ 递增 a[i] 之前分配 i?

c++ - Windows C++ 如何调用从一个线程到另一个线程的阻塞读取?

multithreading - 这里需要 volatile 吗?

javascript - 更改输入值 onclick 按钮 - 纯 javascript 或 jQuery

html - 使用 css 使输入聚焦时 LI 处于事件状态

c - 有没有办法让类变量像虚拟变量一样具有setter/getter?

java - Intellij IDEA Evaluate Expression 窗口和 Thread.currentThread().isInterrupted() 值

ios - 仅允许访问 HTML5 中的相机设备

文件的计算