Search code examples
c++matlabopenmpmex

Matlab exits without error upon clear mex with openMP


I ran into a weird case where Matlab closes without an error.

I have the following mex file that uses OpenMP

// main.cpp
#include "mex.h"
#include "omp.h"

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    int num_threads;
    int kx;
#pragma omp parallel for
    for (kx = 0; kx < 100; kx++)
    {
        if (kx == 0) num_threads = omp_get_num_threads();
        float tmp = (float)kx;
    }
    mexPrintf("Num threads: %i\n", num_threads);
}

When I compile this with mex COMPFLAGS="$COMPFLAGS /openmp" main.cpp -output test_openmp and run it, it works as expected

>> test_openmp()
Num threads: 8

However, if I immediately add a clear mex after the call, Matlab crashes and immediately closes without error report.

>> test_openmp(); clear mex

If I add a pause(1), there is no crash

>> test_openmp(); pause(1); clear mex

This is a problem in another program where call a mex program can case an error and I need to do:

try
    mexprogram()
catch ME
    clear mexprogram
end

Does anybody know what is going on? When I run Matlab from the command line, I see the following return code: -1073741819. Attaching the debugger does not give any info.

I am using MSVC 2022 and Matlab R2021b.


Update

Linking against the intel openMP implementation libiomp5md.lib fixes the issue! Compiling from MATLAB with

mex -v -g COMPFLAGS="$COMPFLAGS /openmp" LINKFLAGS="$LINKFLAGS /nodefaultlib:vcomp" '-LC:\Program Files\MATLAB\R2021b\bin\win64\' -llibiomp5md.lib main.cpp -output test_openmp_intel

Solution

  • The problem comes from mixing different openmp implementations. Linking with the intel openmp lib that comes with Matlab solves the issue.

    Compile with

    mex -v -g COMPFLAGS="$COMPFLAGS /openmp" LINKFLAGS="$LINKFLAGS /nodefaultlib:vcomp" '-LC:\Program Files\MATLAB\R2021b\bin\win64\' -llibiomp5md.lib main.cpp -output test_openmp_intel