Matlab-mex 代码中的计数器在预定迭代后不会停止



我正在使用OpenMP在Matlab的mex文件中运行一个循环,并且在达到预定的迭代次数后它不会停止。

我用这个命令编译文件:

mex myfile.c CFLAGS= $CFLAGS -fopenmp LDFLAGS=$LDFLAGS -fopenmp

我的代码看起来像这样:

#include <stdio.h>n'
#include "mex.h"n'
#include "omp.h"n'
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    int i;
    int numthreads = 8;
    #pragma omp parallel for default(none) num_threads(numthreads) private(i)
    for (i = 0; i < 20; i++) {
        int tid = omp_get_thread_num();
        printf("Hello world number %d from omp thread %dn", i, tid);
    }
}

我希望通过"你好世界19..."得到"Hello world 0...",每个只有一个,无论顺序如何。相反,他们不断无限期地重复。

Hello world number 0 from omp thread 0
Hello world number 1 from omp thread 0
Hello world number 2 from omp thread 0
Hello world number 3 from omp thread 1
Hello world number 4 from omp thread 1
Hello world number 5 from omp thread 1
Hello world number 12 from omp thread 4
Hello world number 13 from omp thread 4
Hello world number 16 from omp thread 6
Hello world number 17 from omp thread 6
Hello world number 18 from omp thread 7
Hello world number 19 from omp thread 7
Hello world number 6 from omp thread 2
Hello world number 7 from omp thread 2
Hello world number 8 from omp thread 2
Hello world number 8 from omp thread 2
Hello world number 9 from omp thread 3
Hello world number 10 from omp thread 3
Hello world number 11 from omp thread 3
Hello world number 14 from omp thread 5
Hello world number 15 from omp thread 5
Hello world number 0 from omp thread 0
Hello world number 1 from omp thread 0
Hello world number 2 from omp thread 0
Hello world number 12 from omp thread 4
Hello world number 13 from omp thread 4

printf被转换为 mexPrintf ,这会导致给定的格式化字符串显示在 MATLAB 命令窗口中。您没有在此处使用printf的 C 库。 mex.h声明一个宏来进行此转换。

MATLAB MEX 接口不是线程安全的。您不能从除主线程之外的任何线程调用这些函数。

因此,您可能会遇到一些由从多个线程调用mexPrintf引起的未定义行为。

作为解决方法,请考虑写入文件。 fprintf不会被 MEX 接口取代,但不能使用它写入 MATLAB 命令窗口。

最新更新