9

我在一段并行代码中使用多个 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。

4

1 回答 1

1

正如您的问题下方所评论的那样,如果您故意从多个线程调用非线程安全的封闭源代码库的函数而没有同步,那么行为是不可预测的,您应该避免这样做。一个可能的想法是跨多个进程跨越对 MATLAB 引擎的调用,但请考虑这可能会增加复杂性(需要进程间同步)并恶化性能。

顺便说一句,C++11 及更高版本的用户应该使用新的MATLAB Engine API for C++ 进行编程。请注意engOpenSingleUse,在新 API 中至少没有明确的等效功能(最接近的替换是matlab::engine::startMATLAB)。

于 2019-02-22T05:53:38.877 回答