2

I have the following simple C code which is compiled in MATLAB using mex -v COMPFLAGS="$COMPFLAGS -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 running this code i get the following output

max threads = 6
ID = 0
nThreads = 1
End

How come only 1 thread is ran? If i move the code from Mex and just compile it as a normal C file, this produces the expected output(so ID=0-5 and nThreads = 6)

I have read Why is OpenMP in a mex file only producing 1 thread? , however the answer was to ensure OpenMP support when compiling which i feel like i have already done.

Anyone who can help?

Anders
  • 61
  • 4
  • Try adding `num_threads(6)` to your pragma. – Cris Luengo May 05 '20 at 14:04
  • Check that the resulting binary use OpenMP with `ldd`. Moreover, try to run the computation with the environment variable `OMP_DISPLAY_ENV` defined and set to `TRUE`: if OpenMP informations are written in your terminal, it means the OpenMP runtime is loaded. – Jérôme Richard May 05 '20 at 18:18

1 Answers1

3

So i figured out what was wrong, so posting here in case anyone encounters the same problem.

Compiling with mex -v CFLAGS="$CFLAGS -fopenmp" LDFLAGS="$LDFLAGS -fopenmp" MEXTESTER.c did the trick. Not sure why i had to use CFLAGS, when as far as i can tell, the mex documentation specifies that this is for macOS or linux.

Moreover i also had to remove printf() statements from within the parallel region. If i tried to print from anything but thread 0 inside the parallel region, MATLAB just crashed.

Anders
  • 61
  • 4
  • [The documentation](https://www.mathworks.com/help/matlab/ref/mex.html#btw193g-1) says "For the MinGW-w64 compiler, which is based on gcc/g++, use the Linux® compiler flags." So this makes sense. – Cris Luengo May 05 '20 at 20:10
  • `printf` is replaced by `mexPrintf` in MEX-files (mex.h defines a preprocessor macro for this replacement). All the `mex...` functions must be used only from the main thread, the MATLAB interpreter is not thread-safe. – Cris Luengo May 05 '20 at 20:11
  • Yeah, i see the documentation mentioning that MinGW should use Linux compiler flags. Did not notice that before, so that was rather dumb. – Anders May 05 '20 at 20:27
  • No, it's not dumb. It's easy to overlook. I just went looking through the documentation to see if there was a confirmation of your findings. :) – Cris Luengo May 05 '20 at 20:30