c ++ fstream并发访问 [英] c++ fstream concurrent access

查看:180
本文介绍了c ++ fstream并发访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果文件是从不同的进程/线程并发访问的,会发生什么?
我知道没有标准的方法锁定文件,只有os特定的函数。

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.

在我的例子中,文件将被经常读取和写入很少。
现在如果 A 打开要读取的文件(ifstream)并开始读取块。并且 B 打开用于写入(ofstream)的同一个文件并开始写入。会发生什么?是否有定义的行为?

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?

编辑
我的目标是并发读取,写入许多文件。但是写访问不会经常发生。如果fstreams保证文件内容不会混淆,我会满意。

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.

例如:
进程1和2写入文件A.如果它们写并发我不关心1或2的版本是否写入光盘,只要它是文件的一致版本。

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.

如果fstreams不处理我将使用一个数据库。

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

推荐答案

使用C ++,有效的文件共享(同时访问)

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


  1. 您可以使用锁定文件共享文件。打开foo.dat之前,尝试创建文件foo.lock。保持循环,直到成功。访问后,删除foo.lock。这允许串行访问,但不能并发访问。

  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.

您可以在平台特定的方式中使用字节级锁定。 Windows具有LockFileEx()。 POSIX有fcntl和flock。如果你需要多平台,你将需要单独的实现。您可以将它们封装在类中,并使用#if来处理平台特定的位。
这是最高效的(最快的),但它涉及非常复杂的编程,并容易出错。

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.

DBMS。

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.

这篇关于c ++ fstream并发访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆