MEX Development Notes - sjhstone/MATLAB_Develop_Tips GitHub Wiki

OpenMP

OpenMP implementation

Version 1.0 2.0 2.5 3.0 3.1 4.0 4.5 5.0 5.1
Year 1998 2002 2005 2008 2011 2013 2015 2018 2020
GCC --- --- 4.2+ 4.4+ 4.7+ 4.9+ 6+ 9+ ---
ICC 19.1 โ— โ— โ— โ— โ— โ— โ— โ— ---
MSVC 19 โ— โ— --- --- --- --- --- --- ---
Clang 12 โ— โ— โ— โ— โ— โ— โ— ๏ฟฎ ---

Operating system support

Compiler GCC ICC MSVC Clang
Linux native --- --- ---
macOS --- --- --- native
Windows MinGW native native ---

References:

Commands for compilation

Remember to set environment variable to a suitable value first.

setenv('OMP_NUM_THREADS', '4');

On UNIX-like systems

mex CFLAGS="$CXXFLAGS -fopenmp" LDFLAGS="$LDFLAGS -fopenmp" src.c
mex CXXFLAGS="$CXXFLAGS -fopenmp" LDFLAGS="$LDFLAGS -fopenmp" src.cpp

On Windows

mex COMPFLAGS="$COMPFLAGS /openmp:experimental" src.c

Implementation conflict consideration

Microsoft Visual C++ will by default link your objects to Microsoft's OpenMP implementation, gcc/g++ will typically link against libgomp (GNU OpenMP). MATLAB itself makes use of Intel's OpenMP implementation however, this can lead to incompatibilities when executing your MEX-file linked against Microsoft OpenMP or GOMP, in MATLAB. To prevent running into these incompatibilities we recommend you also use Intel's OpenMP implementation in your MEX-files. The following page on the Intel website explains how various non-Intel compilers and linkers (like gcc/g++ and Microsoft Visual C++) can be used to compile code for- and link against Intel's OpenMP:

Source: https://www.mathworks.com/matlabcentral/answers/237411-can-i-make-use-of-openmp-in-my-matlab-mex-files#answer_190619

Thread-safe consideration

Examples of API function that do not allocate memory (and hence are thread-safe): mxGetPr, mxGetPi, mxGetIr, mxGetJc, mxGetNumberOfDimensions, etc.

Examples of API functions that do allocate memory (and hence are not thread-safe): mxArrayToString, mxCreateDoubleMatrix, mxCreateNumericArray etc.

Questionable: mxGetDimensions if mwSize does not match size_t

Source: https://www.mathworks.com/matlabcentral/answers/237411-can-i-make-use-of-openmp-in-my-matlab-mex-files#answer_190663