Mex file with OpenMP - Unexpected behavior
1 次查看(过去 30 天)
显示 更早的评论
I am trying to create a mex file using the multi-theading support provided by OpenMP.
The following code is my simple test program. The problem is that instead of opening a new thread for each iteration, the complete for loop is executed in a separate thread.
The code:
#include "mex.h"
#include <stdio.h>
#include <omp.h>
void mexFunction(int nlhs,mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
int count;
int th_id;
#pragma omp parallel for private(count) num_threads(3)
for( count = 0; count < 3; count++ )
{
th_id = omp_get_thread_num();
printf("Hello World from thread %d, %d\n", th_id, count);
}
printf( "Finished\n" );
}
The output:
Hello World from thread 0, 0
Hello World from thread 0, 1
Hello World from thread 0, 2
Hello World from thread 0, 0
Hello World from thread 0, 0
Hello World from thread 0, 1
Hello World from thread 0, 2
Hello World from thread 0, 1
Hello World from thread 0, 2
Finished
I run the following line to compile the code:
mex myFile.c CFLAGS="\$CFLAGS -fopenmp" LDFLAGS="\$LDFLAGS -fopenmp"
I am using Matlab 2008a, and my system is Red Hat Linux, with gcc version 4.1.2 (Red Hat has support for OpenMP since version 4.1 so this should not be an issue).
Any help is greatly appreciated,
Michael
0 个评论
回答(1 个)
James Tursa
2012-5-10
One thing for sure is you need to make th_id private (but that is just a printing issue that would not affect the total number of iterations executed). Other than that I don't see an issue. It runs fine on Windows MS Visual Studio, so I would hazard a guess that it is a compiler bug. You might try splitting the omp constructs up. E.g.,
#include "mex.h"
#include <stdio.h>
#include <omp.h>
void mexFunction(int nlhs,mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
int count;
int th_id;
#pragma omp parallel private(count,th_id) num_threads(3)
{
#pragma omp for
for( count = 0; count < 3; count++ )
{
th_id = omp_get_thread_num();
printf("Hello World from thread %d, %d\n", th_id, count);
} printf( "Finished\n" );
}
}
3 个评论
James Tursa
2012-5-11
It could be that your particular compiler OpenMP conflicts with MATLAB somehow. I know that this is the case for some compilers. E.g., Intel Fortran 9.1 OpenMP will not work with MATLAB, even though it works fine in a standalone executable.
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!