c# - 同时从单个 Matlab dll 调用两个函数

标签 c# multithreading matlab

我创建了一个包含两个函数的 Matlab dll。 Function1 运行需要 3-4 毫秒,Function2 需要大约 1 秒。我需要在 C# 中连续运行 Function1,不时运行 Function2。我遇到过,当我运行 Function2 时,Function1 不会连续运行,或者它花费的时间远远超过 3-4 毫秒(在 2-3 秒的范围内)。 Function2 完成后,Function1 立即返回正常/快速状态。这些是我已经尝试过的:

  1. 我在一个单独的线程中调用了 Function2,但没有成功! (Function1 也在单独的线程中运行)。
  2. 我使用了 backgroundworker 而不是 Thread(以防万一),但运气不好!
  3. 我为 Function2 创建了一个单独的 dll,但我再次遇到了同样的问题/延迟/延迟。

有没有人对这个问题有任何想法/解决方案? Matlab 是否在单线程中运行函数/代码?如果没有,是否有为函数指定单独的线程?

感谢任何帮助。

最佳答案

看来您的直觉是正确的:对 Matlab 库的调用是按顺序执行的,即使来自多个线程也是如此。请参阅 Peter Webb 在 Creating C++ Shared Libraries and DLLs 下的评论:

You can call the libraries from multiple threads, but only one thread can be active in a library at any time. The generated libraries are protected by semaphores, which only allow one user thread into the generated library at any one time. Other user threads that try to call into the shared library will block (wait) until the shared library is “free”.

[...]

The libraries protect themselves with semaphores. They do so because the underlying execution engine (the MCR) is not thread safe. This means that even if you could disable the semaphores, you wouldn’t want to, since you’d likely get incorrect results or program failures.

If you truly need parallelism, currently your best (and only) option is to use separate processes. If your client can speak any of the standard web protocols (HTTP or JSON) or Microsoft’s proprietry extended versions, it’s pretty simple to set up web-based WCF clients in separate processes using WCF. (Of course, your servers have to run on Windows machines in that case.) See my WCF post for details.

关于c# - 同时从单个 Matlab dll 调用两个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27649939/

相关文章:

matlab - 工作区,.m脚本和Simulink模型之间的关系是什么,如何有效使用它们?

c# - 如何在两个 DataGridView 控件之间绘制线条

java - java 多线程循环法

java - 跟踪执行线程

java - Spring 集成 : Message released twice after delay

matlab - MATLAB 是否使用 OpenCv CascadeClassifier?

java - java服务器和matlab客户端之间的通信

c# - 随机调用不存在的 style.css 操作 - 为什么?

c# - 在 C# 中通过 XML 发送潜在敏感数据

c# - 类调试,如何知道从哪里调用类