Multithreading in MEX function using pthreads

6 views (last 30 days)
I am building a multi-threaded MEX function which uses pthreads. I followed the example from http://robertoostenveld.nl/?p=33, and everything is going fine, except that I get a segmentation fault every time pthread_join() is called (works fine if I comment out pthread_join, but I need this functionality). Here is the output from gdb when this happens:
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7fffe35ea700 (LWP 20687)]
0x00007ffff4c5ef53 in pthread_join () from /lib/libpthread.so.0
Here is a simplified version of the code in my mexFunction():
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
struct stableParams params;
/* Assign pointers to each input */
params.remCodePhase = *mxGetPr(prhs[0]);
params.remCarrPhase = *mxGetPr(prhs[1]);
/* etc */
/*struct funcArgs args[params.n_threads]; */
/* Create matrix for the return argument. */
plhs[0] = mxCreateDoubleScalar(0);
plhs[1] = mxCreateDoubleScalar(0);
/* etc */
/* Assign pointers to the output */
params.remCodePhaseOut = mxGetPr(plhs[6]);
params.remCarrPhaseOut = mxGetPr(plhs[7]);
/* etc */
struct Correlators correlators[params.n_threads];
params.correlators[params.n_threads] = correlators;
pthread_t threads[params.n_threads];
int rc, t;
for(t=1; t <= params.n_threads ; t++){
struct funcArgs *args = mxMalloc(sizeof(*args));
if (args){
args->params = params;
args->curr_thread = t;
mexPrintf("In main: creating thread %d\n", t);
rc = pthread_create(&threads[t], NULL, do_thread, (void *)args);
if (rc){
mexErrMsgTxt("problem with return code from pthread_create()");
}
}
}
int *ptr;
for(t=0; t< params.n_threads; t++){
int rc2=pthread_join(threads[t],(void**)&(ptr));
}
It's very possible I'm doing something wrong because I'm new to both C and pthreads. But has anyone managed to get pthreads working in a MEX function? I'm using, by the way, Ubuntu 10.04 and Matlab 2013a.

Answers (1)

Jan
Jan on 1 Jul 2013
Edited: Jan on 1 Jul 2013
Do the threads reply a value by pthread_exit() or not? You call pthread_join twice, one time without catching the output and one time with it. You have to decide for one of the methods.
[EDITED] do_thread creates the variable used as output dynamically, such that the memory is released when the function returns. Then catching the pointer in the caller fails. Please try this:
int *ret2 = malloc(sizeof(int));
*ret2 = 200;
pthread_exit((void *) ret2)
  2 Comments
Robert
Robert on 1 Jul 2013
Sorry, first call of pthread_join was a mistake. I meant to remove that. To answer your question, yes, I call pthread_exit with a return value, e.g.:
int ret2 = 200;
pthread_exit(&ret2)

Sign in to comment.

Categories

Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!