To speed up some heavy calculations I wrote a C file with I compiled with Matlabs mex compiler. It appears to run smoothly giving correct results when using only single threads/no parfor loops and I have run it > 100 times without any error.

However, when I run several calculations in parallel, one or two of my workers usually die, which lets the parfoor loop restart. After a while though all workers are able to finish. These calculations are done using SLURM, so on another machine in our network. Anyone got an idea? Perhaps my MexFile does something illegal I am not aware of.

My main script has this structure:

`parfor i=1:numWorkers doWork();end`

and doWork() is basically like

`function doWork()doSomestuff();[a,b,c,d,e,f] = initialize();myMexFunc(a,b,c,d,e,f);doMoreStuff();end`

and my Mex file is the following:

`#include "mex.h"#include "stdio.h"void calcModulation(double* A, unsigned int* B, double* C, unsigned int* D, unsigned int L, double* E, unsigned int num_col, double* F){ // First Task for(unsigned int n=0;n < L; ++n) { for(unsigned int m=0; m < 132; ++m) { A[D[n]+ 22*(B[n]+m)] = A[D[n] + 22*(B[n]+m)] + C[m+132*n]; } }// Second Task for(unsigned int n=0;n < num_col; ++n) { for(unsigned int m=0; m < 22; ++m) { E[n] = E[n] + F[m + 22*(n)] * A[m + 22*(n)]; } } }/* The gateway function */void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ // Names changed as part of the original code is secret unsigned int num_col = mxGetN(prhs[0]); unsigned int L = mxGetN(prhs[2]); double* myMatrix_A = mxGetData(prhs[0]); // N x L unsigned int *myVector_C, *myVector_D; myVector_C = (unsigned int*) mxGetData(prhs[1]); // N x 1 double* myMatrix_B = mxGetData(prhs[2]); // N x L myVector_D = (unsigned int*) mxGetData(prhs[3]); // N x 1 double* myVector_E = mxGetData(prhs[4]); //1 x L double* myMatrix_D = mxGetData(prhs[5]); //N X L calcModulation(myMatrix_A, myVector_C, myMatrix_B, myVector_D, L, myVector_E, num_col, myMatrix_D); }`

Is there something wrong about the way I set the pointers in the mex file?

The dimensions of the Matlab variables are stated next to the "mxGetData" calls. All are double except for those casted to unsigned int*.

## Best Answer