Matlab crashes in simple MEX C "#pragma omp parallel for" test example
1 view (last 30 days)
Show older comments
The program below crashes randomly (It appears to be random, it sometimes works). It feels like it might be me misunderstanding some basic thing. If so, I apologize in advance. Please let me know if I can provide more info. I compile using:
>>mex parallel.c CFLAGS="\$CFLAGS -fopenmp" LDFLAGS="\$LDFLAGS -fopenmp"
I am running this on Max OS 10.8.2 and Matlab 7.14.0.739 (R2012a) 64bit. My GCC version is "i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)".
PROGRAM BELOW:
#include "mex.h"
#include <omp.h>
/* Parallel part of program */
double inner_loop(){
double sum;
int p, n;
sum = 0.0;
n = 100;
#pragma omp parallel for shared(n) private(p) reduction(+: sum)
for(p = 0; p<n; p++){
sum += 1.0;
}
return sum;
}
/* Main function */
void mexFunction(
int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]
)
{
/* Initialize variables */
int i, m;
double sum;
/* Set values */
m =100;
sum = 0.0;
/* Outer loop */
for(i=0; i<m; i++){
sum += inner_loop(); // Call parallel inner loop
}
/* Output data */
plhs[0] = mxCreateDoubleMatrix(1,1, mxREAL);
double* y = mxGetPr(plhs[0]);
y[0]=sum;
return;
}
0 Comments
Answers (2)
James Tursa
on 2 Oct 2012
Edited: James Tursa
on 2 Oct 2012
There might be some incompatibility between the OpenMP implementation of your compiler and MATLAB. Maybe try something even simpler first and then build from there. E.g.,
#include "mex.h"
#include <omp.h>
void mexFunction(
int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]
)
{
int p, n;
double sum;
sum = 0.0;
n = 100;
#pragma omp parallel for shared(n) private(p) reduction(+: sum)
for(p = 0; p<n; p++){
sum += 1.0;
}
mexPrintf("sum = %f\n",sum);
}
1 Comment
See Also
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!