[英]How to use OpenMP in my MEX-file without crashing MATLAB?
我從 Visual Studio 2019 構建了一個 Windows MEX 文件。我的 MATLAB 版本是 R2019a。 該代碼只是對兩個輸入 matlab 數組進行了一些“排序”。 這是我嘗試與 OpenMP 一起使用的示例。 “測試.cpp”
#include "mex.h"
#include <vector>
#include <iostream>
#include <algorithm>
#include <omp.h>
using namespace std;
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
mxDouble *p0 = mxGetDoubles(prhs[0]);
mwSize size0 = mxGetNumberOfElements(prhs[0]);
mxDouble* p1 = mxGetDoubles(prhs[1]);
mwSize size1 = mxGetNumberOfElements(prhs[1]);
vector<vector<int>> v(2);
int i;
for (i = 0; i < size0; i++) {
v[0].push_back(int(*p0++));
};
for (i = 0; i < size1; i++) {
v[1].push_back(int(*p1++));
};
#pragma omp parallel for
for (i = 0; i < 2; i++) {
sort(v[i].begin(), v[i].end());
};
plhs[0] = mxCreateCellMatrix(2, 1);
for (int i = 0; i < 2; i++) {
mxArray* str = mxCreateNumericMatrix(1, v[i].size(), mxDOUBLE_CLASS, mxREAL);
copy(v[i].begin(), v[i].end(), mxGetPr(str));
mxSetCell(plhs[0], i, mxDuplicateArray(str));
mxDestroyArray(str);
};
return;
}
我的測試 M 文件是:
a1= [1,2,3,4,5];
a2= [1,1,1,1];
result = test(a1,a2);
clear mex;
理想的 output result
將是 2*1 單元格。 如果我刪除# pragma
行,則 MEX 文件運行良好。 如果我添加它,MATLAB 崩潰了。 幾天來我一直試圖找到問題並沒有找到任何解決方案。 除了,
mexPrintf
。 我聽說 function 會使用 OpenMP 使 MEX 文件崩潰。plhs[0] = mxCreateCellMatrix(2, 1);
的最后一部分進入#pragma
並行部分。 如上面的代碼,我做對了嗎? 您不能在代碼的並行部分調用任何mx...
或mex...
函數*。 您必須在並行部分之前獲取指向所有數據的指針,包括創建 output arrays 並獲取它們的指針,然后僅並行執行計算。
* 這里給出的規則過於寬泛,一些mx...
函數可能可以在並行部分中使用,如James Tursa 的評論所示。 我不喜歡猜測並保持規則簡單。
這可能不是完美的解決方案。 我剛剛對代碼進行了一些更正,並成功在 Matlab 中構建了 mexw64。 至於在visual studio中編譯代碼,mex跑得很低。(VS構建15s和Matlab構建0.4s我不知道為什么。)首先,我糾正了兩個嚴重錯誤。
#pragma...
的花括號。 左花括號不能直接在#pragma omp parallel
之后。 它應該在一個新行中。 如下,#pragma omp parallel
{
#pragma omp for
for (i = 0; i < 2; i++) {
sort(v[i].begin(), v[i].end());
};
}
2.在並行循環中,不能使用mwIndex
類型的索引。 它必須是int
類型。 這些問題的代碼中不會發生此錯誤。 我只是記下來。
然后我用mex -v COMPFLAGS="$COMPFLAGS /openmp" test.cpp;
構建 mex 文件。 我只是建議不要在一個 m 文件中構建和應用 mex。 我的 Matlab 有時會崩潰。 我不知道原因。 我剛剛成功地將它們分開,甚至聽起來很奇怪。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.