c++ fstream concurrent access

2019-05-07 10:13发布

What will happen if files are accessed concurrently from different processes/threads? I understand there is no standard way of locking a file, only os specific functions.

In my case files will be read often and written seldom. Now if A open a file for reading (ifstream) and starts reading chunks. And B opens the same file for writing (ofstream) and starts writing. What will happen? Is there a defined behavior?

edit My goal is concurrent read, write access to many files. But write access will not occur very often. I would be content if the fstreams guarantee that file content doesn't get mixed up.

E.g.: Process 1 and 2 write to file A. If they write concurrently I dont't care if the version of 1 or 2 is written to disc, as long as it is a consistent version of the file.

If a process reads a file and another writes to it at the same time, I want the reading process to get the "old" version of the file.

If fstreams don't handle this I will use a database.

2条回答
放荡不羁爱自由
2楼-- · 2019-05-07 10:46

There is certainly no portable way to do efficient file sharing (with simultaneous access) using C++.

  1. You can share files using a "lock" file. Before opening "foo.dat", try to create file "foo.lock". Keep looping until you succeed. After access, delete foo.lock. That allows serial access, but not concurrent access.

  2. You can use byte-level locking in platform-specific ways. Windows has LockFileEx(). POSIX has fcntl and flock. If you need multi-platforms you will need separate implementations. You can encapsulate them in a class and use #if to handle the platform-specific bits. This is the most efficient (fastest) by a lot, but it involves very complex programming and is prone to bugs.

  3. You can use a DBMS.

A DBMS will be simplest by a lot, but it does tie you to an external product which may or may not be a problem. Byte-wise locking is much faster than anything else, but will add a lot to devel and maintenance costs.

查看更多
萌系小妹纸
3楼-- · 2019-05-07 10:50

What is your goal? Are you trying to prevent concurrent read/write operations to files or do you want to implement some form of IPC via files?

Either way, look at boost interprocess, it provides you the opportunity to use file locks (and other cool stuff for IPC) And it has the added advantage of being portable!

查看更多
登录 后发表回答