Mex OpenMP C code

조회 수: 23 (최근 30일)
Yangyang Xu
Yangyang Xu 2019년 1월 22일
편집: sjhstone 2020년 8월 19일
I tried to use OpenMP in Matlab 2018a. My code is very simple, called testOpenMP.c.
I successfully compiled the code by mex -v testOpenMP.c CFLAGS="$CFLAGS -fopenmp" LDFLAGS="$LDFLAGS -fopenmp"
However, we I run the compile mex extension by just typing testOpenMP in Matlab's command window. It always crashed.
Do you know how to correctly compile such an openmp c code and run it?
#include "mex.h"
#include "math.h"
#include "stdio.h"
#include <omp.h>
void mexFunction(
int nargout,
mxArray *pargout [ ],
int nargin,
const mxArray *pargin [ ]
) {
int thread_count = 32;
#pragma omp parallel for default(none)
for(int i = 0; i < 32; i++)
printf("Hello from %d\n",i);
  댓글 수: 5
Yangyang Xu
Yangyang Xu 2019년 1월 22일
It will not happen if I omit the #pragma line.
I used gcc 6.5
Sushant Mahajan
Sushant Mahajan 2019년 5월 4일
Did you find any solution? I am facing the exact same issue with a FORTRAN subroutine using MEX configured with a gfortran-6 compiler.
It runs fine when it is compiled without the -fopenmp flag, but MATLAB shuts down when the subroutine is called after using the -fopenmp flag during compilation. This happens even if I do not use any OMP_PARALLEL (equivalent to C's #pragma omp parallel) construct in the code.

댓글을 달려면 로그인하십시오.

답변 (2개)

Arwel 2019년 9월 19일

sjhstone 2020년 8월 19일
편집: sjhstone 2020년 8월 19일
Both printf and mexPrintf are not thread-safe and should be avoided in multi-thread OpenMP MEX C codes.
You can get more information at


Help CenterFile Exchange에서 Write C Functions Callable from MATLAB (MEX Files)에 대해 자세히 알아보기



Community Treasure Hunt

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

Start Hunting!

Translated by