Linux上C中的标准输出线程安全? [英] stdout thread-safe in C on Linux?

查看:16
本文介绍了Linux上C中的标准输出线程安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Linux 上使用 printf 写入标准输出是线程安全的吗?使用较低级别的 write 命令怎么样?

Is writing to stdout using printf thread-safe on Linux? What about using the lower-level write command?

推荐答案

C 标准没有规定——它取决于你对 C 标准库的实现.事实上,C 标准甚至根本没有提到线程,因为某些系统(例如嵌入式系统)没有多线程.

It's not specified by the C standard -- it depends on your implementation of the C standard library. In fact, the C standard doesn't even mention threads at all, since certain systems (e.g. embedded systems) don't have multithreading.

在 GNU 实现 (glibc) 中,stdio 中处理 FILE* 对象的大多数高级函数都是线程安全的.名称中通常没有 unlocked 的那些(例如 getc_unlocked(3)).但是,线程安全是在每个函数调用级别:例如,如果您对 printf(3) 进行多次调用,则每个调用都保证以原子方式输出,但其他线程可能会打印在您对 printf() 的调用之间进行处理.如果您想确保一系列 I/O 调用以原子方式获得输出,您可以在它们周围加上一对 flockfile(3)/funlockfile(3) 调用来锁定 FILE句柄.请注意,这些函数是可重入的,因此您可以在它们之间安全地调用 printf(),即使 printf() 本身进行调用也不会导致死锁到 flockfile().

In the GNU implementation (glibc), most of the higher-level functions in stdio that deal with FILE* objects are thread-safe. The ones that aren't usually have unlocked in their names (e.g. getc_unlocked(3)). However, the thread safety is at a per-function call level: if you make multiple calls to printf(3), for example, each of those calls is guaranteed to output atomically, but other threads might print things out between your calls to printf(). If you want to ensure that a sequence of I/O calls gets output atomically, you can surround them with a pair of flockfile(3)/funlockfile(3) calls to lock the FILE handle. Note that these functions are reentrant, so you can safely call printf() in between them, and that won't result in deadlock even thought printf() itself makes a call to flockfile().

write(2) 等低级 I/O 调用应该是线程安全的,但我不能 100% 确定 - write() 对内核进行系统调用以执行 I/O.这究竟是如何发生的取决于您使用的内核.它可能是 sysenter 指令,或旧系统上的 int(中断)指令.一旦进入内核,就由内核来确保 I/O 是线程安全的.在我刚刚使用 Darwin Kernel Version 8.11.1 进行的测试中,write(2) 似乎是线程安全的.

The low-level I/O calls such as write(2) should be thread-safe, but I'm not 100% sure of that - write() makes a system call into the kernel to perform I/O. How exactly this happens depends on what kernel you're using. It might be the sysenter instruction, or the int (interrupt) instruction on older systems. Once inside the kernel, it's up to the kernel to make sure that the I/O is thread-safe. In a test I just did with the Darwin Kernel Version 8.11.1, write(2) appears to be thread-safe.

这篇关于Linux上C中的标准输出线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆