Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...