我想制作一个可以从 Matlab 调用的 mex 程序,用户可以在其中注册要用于处理的 Matlab 函数。然后程序将使用此函数在后台处理来自另一个程序的数据。mex 程序和外部程序之间的通信是通过一个共享的全局缓冲区进行的,我使用互斥锁来跟踪它。这部分实际上似乎有效。问题是 Matlab 是单线程的,我想在后台处理数据,以便用户可以继续使用 Matlab。由于 Matlab 是单线程的,我的解决方案是创建一个新线程并从中启动 Matlab 引擎。为此,我需要从从 Matlab 调用的 mex 文件中调用 Matlab 引擎。当我尝试这样做时,程序构建正常,但是当我尝试打开一个新引擎时,Matlab 崩溃。使用下面的测试示例,test('process2')
Matlab 停止,当我使用 ctrl-c Matlab 时崩溃。有时使用test('process')
似乎可行,但可能会在十次调用之一中使 Matlab 崩溃。
#include "mex.h"
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>
#include <stdlib.h>
#include <matrix.h>
#include <unistd.h>
#include "engine.h"
void* local_process(void *arg) {
Engine *engine;
engine = engOpen(NULL);
engClose(engine);
}
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]) {
if ( (nrhs<1) || (! mxIsChar(prhs[0])) ) {
mexErrMsgTxt("First argument should be a command (string)");
return;
}
/* Read command string */
int buflen = mxGetNumberOfElements(prhs[0])+1;
char* buf = mxCalloc(buflen, sizeof(char));
if (mxGetString(prhs[0], buf, buflen) != 0)
mexErrMsgTxt("Could not read command string");
mexPrintf("Command: %s\n",buf);
if (strcmp(buf,"process")==0) {
pthread_t thread;
pthread_create(&thread,NULL,local_process,NULL);
}
else if (strcmp(buf,"process2")==0) {
Engine *engine;
engine = engOpen(NULL);
engClose(engine);
}
}