필터 지우기
필터 지우기

OpenMP in mex file only produces 1 thread

조회 수: 27 (최근 30일)
Anders Melander
Anders Melander 2020년 5월 5일
댓글: James Tursa 2020년 5월 5일
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
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
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
Anders Melander
Anders Melander 2020년 5월 5일
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 2020년 5월 5일
Ah yes, good catch on the printf( ) ... thread safe is implementation dependent.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB Compiler에 대해 자세히 알아보기

태그

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by