如何同步访问 NAS 上的文件的两个进程? [英] How can I synchronize two processes accessing a file on a NAS?

查看:61
本文介绍了如何同步访问 NAS 上的文件的两个进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

事情是这样的:我有两个应用程序,用 C++ 编写并在两台具有不同操作系统(一台 Linux 和一台 Windows)的机器上运行.其中一个过程负责更新 NAS(网络附加存储)上的 XML 文件,而另一个则读取该文件.

Here's the thing: I have two applications, written in C++ and running on two machines with different OS (one Linux and one Windows). One of this process is in charge of updating an XML file on a NAS (Network Attached Storage) while the other one reads this file.

是否可以同步这两个进程以避免在修改文件的同时读取文件?

Is it possible to synchronize these two processes in order to avoid reading of the file at the same time it's being modified?

推荐答案

您可以在服务器上创建一个锁文件,该文件在您执行写入之前创建,等待然后写入并在完成时删除.让读取过程检查读取文件之前的令牌.

You could create a lock file on the server that is created before you do a write, wait then write and delete on completion., Have the read process check for the token before reading the file.

编辑:为了解决评论,您可以实现双重检查锁定类型模式.让读者和作者都有一个锁定文件并在工作之前仔细检查,例如:

Edit: To address the comments, you can implement a double-checked locking type pattern. Have both reader and writer have a locking file and double check before you do work, something like:

Reader:检查写锁定文件,创建读锁定文件,检查写锁定文件,如果存在则删除读文件并中止.

Reader: Check for write lock file, create read lock file, check for write lock file, if exists delete read file and abort.

Writer:检查读锁文件,创建写锁文件,检查读锁文件,如果存在则删除写锁文件并中止.

Writer: Check for read lock file, create write lock file, check for read lock file, if exists delete write lock file and abort.

这将阻止您的进程相互践踏,但可能会发生潜在的竞争条件,因为您可能会同时检查、创建和重新检查两个进程,尽管这不会导致以不一致的状态读取数据,但会导致读取和写入进程在您指定的延迟内中止

This will stop your processes trampling on each other but a potential race condition may occur in that the you could potentially have both processes check, create then recheck simultaneously though this will not cause the data to be read in an inconsistent state but will cause both read and write processes to abort for your specified delay

这篇关于如何同步访问 NAS 上的文件的两个进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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