フィルターのクリア

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 Center および File ExchangeMATLAB Compiler についてさらに検索

タグ

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by