Mex OpenMP C code

Hi,
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?
Thanks,
#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 comentarios

Jan
Jan el 22 de En. de 2019
Editada: Jan el 22 de En. de 2019
I've formatted the code to make it readable. You can do this by your own also.
What do you observe? "It always crashed" is not really clear.
Yangyang Xu
Yangyang Xu el 22 de En. de 2019
Whenever I ran the compiled code, the Matlab automatically shuts down.
Jan
Jan el 22 de En. de 2019
Editada: Jan el 22 de En. de 2019
Does this happen also, if you omit the #pragma line?
Which compiler do you use?
Yangyang Xu
Yangyang Xu el 22 de En. de 2019
It will not happen if I omit the #pragma line.
I used gcc 6.5
Sushant Mahajan
Sushant Mahajan el 4 de Mayo de 2019
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.

Iniciar sesión para comentar.

Respuestas (2)

sjhstone
sjhstone el 19 de Ag. de 2020
Editada: sjhstone el 19 de Ag. de 2020

0 votos

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 https://walkingrandomly.com/?p=1795

Categorías

Más información sobre Write C Functions Callable from MATLAB (MEX Files) en Centro de ayuda y File Exchange.

Productos

Etiquetas

Preguntada:

el 22 de En. de 2019

Editada:

el 19 de Ag. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by