Clear Filters
Clear Filters

OpenMP in mex file only produces 1 thread

27 views (last 30 days)
I have the following simple C code which is compiled using
mex -v COMPFLAGS="$COMPFLAGS -fopenmp" LDFLAGS="$LDFLAGS -fopenmp" MEXTESTER.c.
I have also tried
mex -v CXXFLAGS="$CXXFLAGS -fopenmp" LDFLAGS="$LDFLAGS -fopenmp" MEXTESTER.c.
I am using MATLAB R2019a, running on Windows 10 Home 64-bit with 6 cores available. Mex is configured to use MinGW64 Compiler.
#include "mex.h"
#include <stdio.h>
#include <omp.h>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){
printf("max threads = %d\n",omp_get_max_threads());
#pragma omp parallel
{
printf("ID = %d\n",omp_get_thread_num());
printf("nThreads = %d\n",omp_get_num_threads());
}
printf("End\n");
return;
}
However when i run this only 1 thread is ran, even though omp_get_max_threads() returns 6. So output is
max threads = 6
ID = 0
nThreads = 1
End
If i move the code from mex and just compile it as a normal C file using MinGW, this produces the expected output(so ID=0-5 and nThreads = 6).
My best guess is that im somehow doing the compiling wrong, but i have been unable to determine why it doesn't work.
Anyone who can help?
  1 Comment
James Tursa
James Tursa on 5 May 2020
Here is what I get with your code and R2017b and MSVS 2013
>> mex('COMPFLAGS="$COMPFLAGS /openmp"','MEXTESTER.c')
Building with 'Microsoft Visual C++ 2013 (C)'.
MEX completed successfully.
>> MEXTESTER
max threads = 4
ID = 0
nThreads = 4
ID = 1
nThreads = 4
ID = 2
nThreads = 4
ID = 3
nThreads = 4
End

Sign in to comment.

Accepted Answer

James Tursa
James Tursa on 5 May 2020
Edited: James Tursa on 5 May 2020
What if you try to force it? E.g.,
#pragma omp parallel num_threads(omp_get_max_threads())
Or maybe
omp_set_num_threads(omp_get_max_threads());
#pragma omp parallel
  2 Comments
Anders Melander
Anders Melander on 5 May 2020
I did try this, however it did not work.
I did end up finding a solution to my problem about an hour ago. Turns out compiling using
mex -v CFLAGS="$CFLAGS -fopenmp" LDFLAGS="$LDFLAGS -fopenmp" MEXTESTER.c
did the trick. I don't know why i have to use CFLAGS, when as far as i can tell the documentation for mex states that this is for macOS and linux.
Moreover compiling this way caused Matlab to crash when calling the mex function. Here it turned out that you can only use printf() statements from the original thread that is also running Matlab(so if i want to print anything from within the parallel region, it can only be done from thread 0).
James Tursa
James Tursa on 5 May 2020
Ah yes, good catch on the printf( ) ... thread safe is implementation dependent.

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB Compiler in Help Center and File Exchange

Tags

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!