I want to make a mex program that can be called from Matlab, where the user can register a Matlab function to be used for processing. The program will then use this function to process data coming from another program in the background. The communication between the mex program and the external program is trough a shared global buffer, which I keep track of with mutex locks. That part actually seems to work. The problem is that Matlab is single-threaded and I want to process data in the background, so that the user can keep working with Matlab. Since Matlab is single-threaded my solution is to create a new thread and start Matlab engine from it. For this I need to call Matlab engine from a mex file called from Matlab. When I try to do this the program builds ok, but when I try to open a new engine Matlab crashes. Using the test example below, if I call the program (from inside Matlab) with test('process2')
Matlab stalls, and when I use ctrl-c Matlab crashes. Using test('process')
sometimes seems to work but crashes Matlab in maybe one of ten calls.
#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);
}
}