在MATLAB中创建文件锁(文件互斥体) [英] atomically creating a file lock in MATLAB (file mutex)

查看:1010
本文介绍了在MATLAB中创建文件锁(文件互斥体)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个简单的已经实现的解决方案,用于在MATLAB中以原子方式创建文件锁。

I am looking for a simple already implemented solution for atomically creating a file lock in MATLAB.

像:

file_lock('create', 'mylockfile'); %this will block until it creates the lock file.
file_lock('remove', 'mylockfile'); %this will remove the lock file:

这个问题已经被问过几次, (例如使用Java FileLock ),
,但我没有找到一个简单的已经实现的解决方案。

This question has already been asked several times, with some proposed solution ideas (such as using Java FileLock), but I didn't find a simple already implemented solution.

您是否知道这样的实施解决方案?

Are you aware of such an implemented solution?

注意:

  • locking file access OR exchanging messages bw Matlab Instances
  • Thread Subject: Safe file mutex without race condition

推荐答案

一个非常简单的解决方案,用于将来自多个工作线程的错误/日志消息组合到单个文件中。每次我想写入该文件,我首先将输出写入线程自己的临时文件。接下来,我使用flock将该临时文件附加到主日志文件。跳过一些细节,这里的想法是:

I've settled on a pretty simple solution for combining error/logging messages from multiple worker threads into a single file. Every time I want to write to that file, I first write the output to the thread's own temporary file. Next, I append that temporary file to the "master" log file using flock. Skipping over some details here, the idea is:

fid=fopen(threadtemp, 'w');
fprintf(fid, 'Error message goes here');
fclose(fid);

runme = sprintf('flock -x %s -c ''cat %s >> %s''', LOGFILE, threadtemp, LOGFILE);
system(runme);

有关详细信息,请参阅flock手册页,但上述调用正在获取日志文件上的eXclusive锁,在锁下运行提供的命令,然后释放它。

See the flock man page for details, but the call above is acquiring an eXclusive lock on the logfile, running the provided Command under the lock, and then releasing it.

这显然只有当你在一个系统有羊群(Linux / OS X,某些类型的文件系统),你正在做一些可以从命令行完成,但我敢打赌,这是一个很常见的用例。

This obviously only works if you're on a system which has flock (Linux/OS X, and only certain types of file systems at that) and you're doing something that can be done from the command line, but I'd bet that it's a pretty common use-case.

这篇关于在MATLAB中创建文件锁(文件互斥体)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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