简体   繁体   English

是std :: ifstream线程安全和无锁吗?

[英]Is std::ifstream thread-safe & lock-free?

I intend to perform opening for reading a single file from many threads using std::ifstream. 我打算使用std :: ifstream执行从多个线程读取单个文件的开放。 My concern is if std::ifstream is thread-safe & lock-free? 我担心的是std :: ifstream是否是线程安全且无锁的?

More details: 更多细节:

  1. I use g++ 4.4 on Ubuntu & Windows XP, 4.0 on Leopard. 我在Ubuntu和Windows XP上使用g ++ 4.4,在Leopard上使用4.0。
  2. Each thread creates its own instance of std::ifstream 每个线程都创建自己的std :: ifstream实例

Thanks in advance! 提前致谢!

That is implementation defined. 这是实现定义。 Standard C++ says absolutely nothing about threading, and therefore any assumptions about threads inherently invoke unspecified or implementation defined behavior. 标准C ++对线程一无所知,因此对线程的任何假设本身都会调用未指定的或实现定义的行为。

We need the platform you are using to be more specific, but it's probably unreasonable to assume ifstream is either thread safe or lock free. 我们需要您使用的平台更具体,但假设ifstream是线程安全的还是无锁的,这可能是不合理的。 If nothing else, there are probably locks involved in the OS level calls that actually do the reading from the file, in which case no true lock-free implementation is possible. 如果不出意外,OS级别调用中可能涉及实际从文件读取的锁定,在这种情况下,不可能实现真正的无锁实现。 Even without that, each read from an ifstream needs to check several format flags, and needs to update the flags bits depending on what occurs during the read. 即使没有它,每次从ifstream读取都需要检查几个格式标志,并且需要根据读取期间发生的情况更新标志位。 (ie istream::good() and istream::operator bool ) Since there is no way all of that can be done atomicly, it's unreasonable to assume much about istream 's thread safety characteristics. (即istream::good()istream::operator bool )由于所有这些都不可能以原子方式完成,因此假设istream的线程安全特性很多是不合理的。

See http://gcc.gnu.org/onlinedocs/libstdc++/manual/using_concurrency.html . 请参阅http://gcc.gnu.org/onlinedocs/libstdc++/manual/using_concurrency.html

As of the writing of that manual page, GCC's standard library defers to the operating system's C stdio file buffering. 在编写该手册页时,GCC的标准库遵循操作系统的C stdio文件缓冲。 They avoid keeping state outside the C FILE structure and achieve some level of safety through it. 他们避免将状态保持在C FILE结构之外,并通过它实现某种程度的安全性。

Since the C stdio library implements a buffer of a single range within the file around the last I/O operation, I don't see how a lock-free implementation is possible. 由于C stdio库在最后一个I / O操作周围的文件中实现了单个范围的缓冲区,因此我没有看到如何实现无锁实现 The operations on a file must be processed serially. 必须连续处理文件上的操作。 Perhaps unbuffered mode could help; 也许无缓冲模式可能会有所帮助; that's a little more research than I'd like to do right now. 这比我现在想做的研究多一点。

All std libraries are thread safe but not "async" safe. 所有std库都是线程安全的,但不是“异步”安全的。 So you can call the same functions from different threads but not on the same objects. 因此,您可以从不同的线程调用相同的函数,但不能在相同的对象上调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM