Matlab引擎API的线程安全
我通过反复试验发现MATLAB引擎函数并不是完全线程安全的。
有人知道规则吗?
通过反复试验发现:
在 Windows 上,与 MATLAB 的连接是通过 COM 进行的,因此适用 COM 单元线程规则。 所有调用必须发生在同一个线程中,但多个连接可以发生在多个线程中,只要每个连接是隔离的。
从下面的答案来看,UNIX上的情况似乎并非如此,只要串行进行调用,就可以从多个线程进行调用。
I have discovered through trial and error that the MATLAB engine function is not completely thread safe.
Does anyone know the rules?
Discovered through trial and error:
On Windows, the connection to MATLAB is via COM, so the COM Apartment threading rules apply. All calls must occur in the same thread, but multiple connections can occur in multiple threads as long as each connection is isolated.
From the answers below, it seems that this is not the case on UNIX, where calls can be made from multiple threads as long as the calls are made serially.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从文档,
From the documentation,
当我第一次开始使用该引擎时,我没有遇到任何有关线程安全的文档,因此我认为它不是线程安全的。
我使用 C++ 类来同步对引擎实例的访问。 对于更多并行处理设计,我实例化了引擎类的多个实例。
(编辑)我在 Solaris 上使用 MATLAB R14。 我使用“engOpen”调用打开引擎,并使用“engClose”关闭它。 当调用 Close 的线程与调用 Open 的线程不同时,我的平台不会崩溃。
When I first started using the engine, I didn't run across any documentation on thread safety, so I assumed that it was not thread-safe.
I use a C++ class to synchronize access to an engine instance. For more parallel processing designs, I instantiate multiple instances of the engine class.
(edit) I'm using MATLAB R14 on Solaris. I open the engine using the 'engOpen' call, and close it using 'engClose'. My platform does not crash when the Close is called by a different thread than the one that called Open.
从用户的角度来看,Matlab 的解释器是纯粹的单线程。 为了安全起见,您可能需要从单个线程进行对引擎的所有访问。
请注意,Matlab 在内部使用了大量线程。 有GUI线程,在最近的几个版本中,解释器可以在幕后使用多个线程。 但是,解释器在语义上等同于单线程解释器(带有中断)。
From a user's perspective, Matlab's interpreter is purely single-threaded. To be safe, you probably need to make all access to the engine from a single thread.
Note that internally, Matlab uses plenty of threads. There are GUI threads, and in the last few versions, the interpreter can use multiple threads behind the scenes. But, the interpreter is semantically equivalent to a single-threaded interpreter (with interrupts).
您可以使用
engOpenSingleUse
而不是使用engOpen
来使多个线程单独工作。 (仅限 Windows)You can use
engOpenSingleUse
instead of usingengOpen
to make more than one thread working separately. (Only Windows)