MATLAB中的信号量和锁 [英] Semaphores and locks in MATLAB
问题描述
我正在研究一个MATLAB项目,在该项目中,我想让两个MATLAB实例并行运行并共享数据.我将这些实例称为MAT_1
和MAT_2
.更具体地说,系统的体系结构是:
I am working on a MATLAB project where I would like to have two instances of MATLAB running in parallel and sharing data. I will call these instances MAT_1
and MAT_2
. More specifically, the architecture of the system is:
-
MAT_1
依次处理图像,使用imread
逐个读取它们,并使用imwrite
输出每个图像的结果. -
MAT_2
使用imread
读取MAT_1
输出的图像,并将其结果输出到其他位置.
MAT_1
processes images sequentially, reading them one by one usingimread
, and outputs the result for each image usingimwrite
.MAT_2
reads the images output byMAT_1
usingimread
and outputs its result somewhere else.
我想我要解决的问题之一是确保MAT_2
完全完成对MAT_1
的输出后,才能读取MAT_1
的图像.
One of the problems I think I need to address is to guarantee that MAT_2
reads an image output by MAT_1
once MAT_1
has fully finished writing to it.
我的问题是:
- 您将如何解决这个问题?我是否需要使用信号灯或锁来防止出现竞争状况?
- MATLAB是否提供任何锁定文件的机制? (即类似于
flock
的内容,但直接由MATLAB提供,并且可以在多种平台(例如Windows和Linux)上运行.如果不是,您是否知道我可以用来在MATLAB中构建此机制的任何第三方库?
- 正如@yoda在下面指出的那样,并行计算工具箱(PCT)可以阻止MATLAB工作者之间的调用,这很棒.就是说,我对不需要PCT的解决方案特别感兴趣.
-
为什么需要
MAT_1
和MAT_2
才能在并行线程中运行?:EDIT :
- As @yoda points out below, the Parallel Computing Toolbox (PCT) allows for blocking calls between MATLAB workers, which is great. That said, I am particularly interested in solutions that do not require the PCT.
Why do I require
MAT_1
andMAT_2
to run in parallel threads?:在
MAT_2
中完成的处理平均比MAT_1
慢(并且更容易崩溃),并且MAT_1
的输出为不需要等待的其他程序和过程(包括人工检查)提供了支持.MAT_2
来完成其工作.The processing done in
MAT_2
is slower on average (and more prone to crashing) thanMAT_1
, and the output ofMAT_1
feeds other programs and processes (including human inspection) that do not need to wait forMAT_2
to do its job.- 有关允许实现信号量但不依赖PCT的解决方案,请参见下面的乔纳斯(Jonas)的回答
- 有关解决该问题的其他好的方法,请参见下文Yoda的答案
推荐答案
我个人将使用并行处理工具箱.
Personally, I'd use the parallel processing toolbox for this.
据我所知,在Matlab中没有简单的方法来拥有系统范围的文件锁.但是,为了确保在文件完成写入后,Matlab#2仅读取Matlab#1的输出,我建议在写入例如文件
results_1.mat
之后,Matlab#1写入第二个文件results_1.finished
,即一个空的文本文件.由于第二个文件是在第一个文件之后写入的,因此它的存在表明结果文件已被写入.因此,您可以搜索扩展名为finished
(即dir('*.finished')
)的文件,并使用fileparts
来获取要通过Matlab#2加载的.mat文件的名称.As far as I know, there is no straightforward way in Matlab to have systemwide file locks. However, in order to ensure that Matlab #2 only reads output of Matlab #1 when the file has finished writing, I suggest that after writing e.g the file
results_1.mat
, Matlab #1 writes a second file,results_1.finished
, which is an empty text file. Since the second file is written after the first, its existence signals that the results-file has been written. You can thus search for files with the extensionfinished
, i.e.dir('*.finished')
, and usefileparts
to get the name of the .mat file you'd like to load with Matlab #2.这篇关于MATLAB中的信号量和锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!