C ++ fstream concurrent access

What happens if files are accessed simultaneously from different processes / threads? I understand that there is no standard way to lock a file, but only special functions.

In my case, files will often be read and written rarely. Now, if A open the file for reading (ifstream) and start reading fragments. And B opens the same file for writing (ofstream) and starts writing. What will happen? Is there any specific behavior?

change My goal is to simultaneously read, write to many files. But access to the recording will not occur very often. I would be pleased if fstreams guarantee that the contents of the file will not be confused.

etc .: Process 1 and 2 are written to file A. If they write at the same time, I am not interested if version 1 or 2 is written to disk, if it is a consistent version of the file.

If the process is reading the file and the other is writing it at the same time, I want the reading process to get the "old" version of the file.

If fstreams do not handle this, I will use the database.

+4
source share
2 answers

Of course, there is no portable way to efficiently share files (with simultaneous access) using C ++.

  • You can share files using the "lock" file. Before opening "foo.dat" try to create the file "foo.lock". Continue the cycle until you succeed. After access, delete foo.lock. This provides sequential access but not concurrent access.

  • You can use byte-level locking depending on the platform. 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 process the bits of a particular platform. This is the most efficient (fast) due to the large number, but it involves very complex programming and is error prone.

  • You can use a DBMS.

The DBMS will be easiest, but will tie you to an external product, which may or may not be a problem. Byte-cloudy blocking is much faster than anything else, but will add a lot of development and maintenance costs.

+7
source

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

Anyway, look at boost interprocess, it gives you the ability to use file locks (and other interesting things for IPC). And he has the added benefit of being portable!

+1
source

All Articles