为什么在mex文件中使用OpenMP只能产生1个线程?

8

我是OpenMP的新手。我有以下代码,使用配置了MSVS2010的Matlab mex编译正常。计算机有8个可用处理器(我也通过使用matlabpool进行了检查)。

#include "mex.h"
#include <omp.h>

typedef unsigned char uchar;
typedef unsigned int uint;
//Takes a uint8 input array and uint32 index array and preallocated uint8 array the same
//size as the first one and copies the data over using the indexed mapping
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] ) 
{
    uint N = mxGetN(prhs[0]);
    mexPrintf("n=%i\n", N); mexEvalString("drawnow");
    uchar *input = (uchar*)mxGetData(prhs[0]);
    uint *index = (uint*)mxGetData(prhs[1]);
    uchar *output = (uchar*)mxGetData(prhs[2]);

    uint nThreads, tid;
#pragma omp parallel private(tid) shared(input, index, output, N, nThreads) num_threads(8) 
    {
        tid = omp_get_thread_num();

        if (tid==0) {
            nThreads = omp_get_num_threads();

        }

        for (int i=tid*N/nThreads;i<tid*N/nThreads+N/nThreads;i++){
            output[i]=input[index[i]];
        }
    }
    mexPrintf("nThreads = %i\n",nThreads);mexEvalString("drawnow");
}

我得到的输出是:
n=600000000
nThreads = 1

为什么我请求创建8个线程,但只有一个线程被创建了?

1个回答

11

唉,典型的情况,花了几个小时尝试失败,然后在发布到SO后5分钟内找到了答案。

这个文件需要使用openmp支持进行mex处理。

mex mexIndexedCopy.cpp COMPFLAGS="/openmp $COMPFLAGS"

我懂你的感受,兄弟。 - CptSupermrkt
在Linux下使用gcc编译器,-fopenmp选项对应的是什么? - linello
2
@linello 是的。实际上,我浪费了几个小时,因为我没有正确传递“-fopenmp”。您需要将其传递给编译器和链接器。对于C ++,请使用mex CXXFLAGS="\$CXXFLAGS -fopenmp" LDFLAGS="\$LDFLAGS -fopenmp" [other options] <file.cpp>(对于C,请使用“CFLAGS”代替“CXXFLAGS”;对于C和C ++,同时使用两者)。 - Nicu Stiurca
1
确实如@SchighSchagh所说,在Linux机器上,我必须确保在编译的每个步骤中都有-fopenmp,所以对我有效的是mex CFLAGS='$CFLAGS -fopenmp' LDFLAGS='$LDFLAGS -fopenmp' COPTIMFLAGS='$COPTIMFLAGS -fopenmp -O2' LDOPTIMFLAGS='$LDOPTIMFLAGS -fopenmp -O2' DEFINES='$DEFINES -fopenmp' -v functionName.F,其中DEFINES仅用于确保-fopenmp出现在第一行编译中。 - user1008139

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接