我在一段并行代码中使用多个 matlab 引擎时遇到了一些问题。我可以使用 engOpenSingleUse
成功生成多个引擎,但无法与多个引擎通信(即调用 engPutVariable
失败)。
一如既往,一个最小的 (VS) 示例:
#include "stdafx.h"
#include <engine.h>
#include <omp.h>
int _tmain(int argc, _TCHAR* argv[])
{
//First spawn the matlab engine sessions
Engine *m_Engines[2];
for (int i = 0; i < 2; i++)
{
m_Engines[i] = engOpenSingleUse(NULL, NULL, NULL);
}
//Then spawn the worker threads...
#pragma omp parallel num_threads(2)
{
// Allocate an engine to each thread
int thread_num = omp_get_thread_num();
Engine *thisEngine = m_Engines[thread_num];
#pragma omp for
for (int i = 0; i < 10000; i++)
{
// Create an mxArray and stick some data in it
mxArray* mM = NULL;
mM = mxCreateDoubleMatrix(1, 1, mxREAL);
double data[1] = { 1.0 };
memcpy((void *)mxGetPr(mM), (void *)data, sizeof(data));
// Send it across to matlab
engPutVariable(thisEngine, "A", mM);
// Run some algorithm
engEvalString(thisEngine, "A=A+1;");
// Retrieve result
mM = engGetVariable(thisEngine, "A");
// Get it out of the mxarray
double A = *mxGetPr(mM);
}
}
return 0;
}
有什么想法吗?我在 Win x64 上使用 Matlab R2012b。
最佳答案
正如您在问题下方评论的那样,如果您故意调用 non-thread safe closed source library 的函数从没有同步的多线程,那么行为是不可预测的,你应该避免这样做。一个可能的想法是跨多个进程调用 MATLAB 引擎,但请考虑这可能会增加复杂性(需要进程间同步)并降低性能。
顺便说一下,C++11 及更高版本的用户应使用新的 MATLAB Engine API for C++ 进行编程。 .请注意,engOpenSingleUse
在新 API 中没有等效功能,至少没有明确显示(最接近 的替代是 matlab::engine::startMATLAB
)。
关于c++ - 并行循环中的 Matlab 引擎,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24923876/