Is std::ifstream thread-safe & lock-free?

独自空忆成欢 提交于 2019-12-18 05:11:55

问题


I intend to perform opening for reading a single file from many threads using std::ifstream. My concern is if std::ifstream is thread-safe & lock-free?

More details:

  1. I use g++ 4.4 on Ubuntu & Windows XP, 4.0 on Leopard.
  2. Each thread creates its own instance of std::ifstream

Thanks in advance!


回答1:


That is implementation defined. Standard C++ says absolutely nothing about threading, and therefore any assumptions about threads inherently invoke unspecified or implementation defined behavior.

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. 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. 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. (i.e. 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.




回答2:


See 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. They avoid keeping state outside the C FILE structure and achieve some level of safety through it.

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. 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.




回答3:


All std libraries are thread safe but not "async" safe. So you can call the same functions from different threads but not on the same objects.



来源:https://stackoverflow.com/questions/2754303/is-stdifstream-thread-safe-lock-free

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!