MathWorks does not specifically test or support using OpenMP in customer written MATLAB MEX-files. The article below discusses a number of points however which should help you in successfully using OpenMP in MEX-files.
To be able to make use of OpenMP you will first of all need a C/C++ compiler which supports OpenMP.
- On Windows: not all supported MEX compilers support OpenMP. For example Microsoft Windows SDK 7.1 does not, neither do many of the Microsoft Visual C++ Express editions which are supported MEX compilers in older MATLAB versions. Typically the Microsoft Visual C++ Professional Editions do support OpenMP however.
- On Mac: the default MEX Compiler in recent MATLAB for Mac versions is clang as included with Xcode 5.x and 6.x. The clang compilers included in Xcode 5 and 6 do not support OpenMP. MathWorks does not offer support whatsoever on trying to use other than the officially supported MEX compilers; in theory it should be possible however to for example use gcc/g++ (compiled by yourself or obtained elsewhere) on Mac to create MATLAB MEX-files.
- On Linux: the supported MEX compilers gcc/g++ typically support OpenMP without problems.
*Incompatibilities between OpenMP implementations*
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:
See the documentation page for "mex" to learn more about how to override the compiler and linker flags when calling "mex" such that you can apply the correct flags. To open this page type "doc mex" in your MATLAB Command Window, or consult the online documentation (note the following link is specific for MATLAB release R2020a):
Further, the Intel OpenMP import libraries (libiomp5.lib/so/dylib) can be found in your bin\win32 or bin\win64 directories for 32- and 64-bit MATLAB on Windows respectively and in the sys/os/glnxa64 directory of your MATLAB installation on Linux and sys/os/maci64 on Mac.
The MATLAB documentation states that "for best results, your version of MATLAB must be the same version that was used to create the MEX-file" but also that "MEX-files are usually backward compatible." For MEX-files which make use of OpenMP and which were linked according to the instructions above, the former holds true but the latter does not. You should rebuild and relink your OpenMP MEX-files for each MATLAB release which you are working with.