是MSVCRT的实现fprintf中()线程安全吗? [英] Is MSVCRT's implementation of fprintf() thread safe?

查看:751
本文介绍了是MSVCRT的实现fprintf中()线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看来,<一个href=\"http://stackoverflow.com/questions/594851/is-glibcs-implementation-of-fprintf-thread-safe\">glibc's实施fprintf中()是线程安全的,但就是这样微软的CRT,以及?

It seems that glibc's implementation of fprintf() is thread-safe, but is that so for Microsoft's CRT, as well?

这是线程安全的,我并不意味着只是崩溃,而且,如果多个线程(在同一进程)调用 fprintf中(),文本不会混合

By thread-safe, I don't mean just crashing, but also that if multiple threads (in the same process) call fprintf(), the texts will not be mixed.

也就是说,例如,如果线程A调用 fprintf中(标准输出,AAAA); 和线程B调用 fprintf中(标准输出 BBBB); 它保证不会混合,成为 aabbaabb

That is, for example, if thread A calls fprintf(stdout, "aaaa"); and thread B calls fprintf(stdout, "bbbb"); it's guaranteed not to mix to become aabbaabb.

有这样的保证?

推荐答案

是的。在多线程运行时库,每个流有一个相关的锁。这把锁在任何呼叫开始收购到printf函数,而不是释放,直到只是printf函数返回前。

Yes. In the multithreaded runtime libraries, every stream has an associated lock. This lock is acquired at the beginning of any call to a printf function and not released until just before that printf function returns.

是由C11要求的行为(没有标准C线程,直到C11的概念)。 C11§7.21.2/ 7-8规定:

This behavior is required by C11 (there was no concept of "threads" in standard C until C11). C11 §7.21.2/7-8 states:

每个流具有相关联的锁,用来prevent数据争当多个
  执行的线程访问的流,并以限制由多个线程执行的流操作的交织。只有一个线程可以保持此锁在一个时间。锁是可重入:一个线程可在给定时间保持锁定多次

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.

这是读,写姿势,或查询流的位置访问之前锁定流的所有功能。他们释放与流相关的锁的访问完成时。

All functions that read, write, position, or query the position of a stream lock the stream before accessing it. They release the lock associated with the stream when the access is complete.

的Visual C ++不完全支持C11,但它确实符合这一要求。一对夫妇的其他Visual C ++ - 具体意见:

Visual C++ does not fully support C11, but it does conform to this requirement. A couple of other Visual C++-specific comments:

只要你不定义 _CRT_DISABLE_PERFCRIT_LOCKS 或使用的的_nolock-后缀的功能,然后在单个流大部分操作是原子的。

As long as you are not defining _CRT_DISABLE_PERFCRIT_LOCKS (which only works with the statically-linked runtime libraries, libcmt.lib and friends) or using the _nolock-suffixed functions, then most operations on a single stream are atomic.

如果您需要跨多个操作原子在一个流,可以通过获取和释放流使用的 _lock_file 和的 _unlock_file

If you require atomicity across multiple operations on a stream, you can acquire the lock for a file yourself by acquiring and releasing the stream lock yourself using _lock_file and _unlock_file.

这篇关于是MSVCRT的实现fprintf中()线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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