フィルターのクリア

Mex file with OpenMP - Unexpected behavior

2 ビュー (過去 30 日間)
Michael
Michael 2012 年 5 月 10 日
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

回答 (1 件)

James Tursa
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
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.
Michael
Michael 2012 年 5 月 11 日
That might be the explanation.
In the meantime, my solution is to create a regular executable and make a system call from Matlab to execute the procedure.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeFortran with MATLAB についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by