OpenMP in mex file only produces 1 thread
27 次查看(过去 30 天)
显示 更早的评论
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 个评论
James Tursa
2020-5-5
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
采纳的回答
James Tursa
2020-5-5
编辑:James Tursa
2020-5-5
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 个评论
James Tursa
2020-5-5
Ah yes, good catch on the printf( ) ... thread safe is implementation dependent.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!