Setting number of OpenMP threads in MATLAB mex function, corrupts max number of threads
Alec Jacobson
October 25, 2012
I wanted to use OpenMP in a MATALB mex function, and I noticed some strange behavior when trying to set the number of threads. Consider this small program:
#include "mex.h"
#include <omp.h>
#define min(X,Y) (X<Y ? X : Y)
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
using namespace std;
// Set up openmp
int nProcessors=omp_get_max_threads();
mexPrintf("Number of processors: %d\n",nProcessors);
// Set to 2 threads
omp_set_num_threads(min(nProcessors,2));
mexPrintf("Using %d out of %d threads\n",min(nProcessors,2),nProcessors);
#pragma omp parallel for
for(int i = 0;i<1000;i++)
{
if(i==0)
{
mexPrintf("Num threads: %d\n",omp_get_num_threads());
}
}
}
If I compile this with:
mex omp_bug.cpp
making sure to have -fopenmp in the compiler flags in mexopts.sh
. Then when I run the program the first time I see:
Number of processors: 8
Using 4 out of 8 threads
Num threads: 4
Which appears to be working correctly. But then I run it again and see:
Number of processors: 4
Using 2 out of 4 threads
Num threads: 2
And again:
Number of processors: 2
Using 2 out of 2 threads
Num threads: 2
and it continues. So it seems that setting the number of threads actually also sets the number of max threads across executions. The interesting thing is that if I recompile with the mex function it resets this number of max threads, so it will run correctly once more. In my case, I just no longer try to set the number of threads and just let OpenMP use all of them.