[英]Parallelize function using OpenMP
我正在嘗試並行運行代碼,但是我對與openmp相關的私有/共享等東西感到困惑。 我正在使用c ++(msvc12或gcc)和openmp。
代碼遍歷循環,循環由一個應並行運行的塊,然后是在完成所有並行處理后應運行的塊組成。 並行處理的順序無關緊要。 代碼如下:
// some X, M, N, Y, Z are some constant values
const int processes = 4;
std::vector<double> vct(X);
std::vector<std::vector<double> > stackVct(processes, std::vector<double>(Y));
std::vector<std::vector<std::string> > files(processes, M)
for(int i=0; i < N; ++i)
{
// parallel stuff
for(int process = 0; process < processes; ++process)
{
std::vector<double> &otherVct = stackVct[process];
const std::vector<std::string> &my_files = files[process];
for(int file = 0; file < my_files.size(); ++file)
{
// vct is read-only here, the value is not modified
doSomeOtherStuff(otherVct, vct);
// my_files[file] is read-only
std::vector<double> thirdVct(Y);
doSomeOtherStuff(my_files[file], thirdVct(Y));
// thirdVct and vct are read-only
doSomeOtherStuff2(thirdVct, otherVct, vct);
}
}
// when all the parallel stuff is done, do this job
// single thread stuff
// stackVct is read-only, vct is modified
doSingleTheadStuff(vct, stackVct)
}
如果對性能更好,則可以將“ doSingleThreadSuff(...)”移入並行循環,但是它需要由單個線程處理。 最內層循環中的功能順序無法更改。
我應該如何聲明#pragma omp內容才能使其正常工作? 謝謝!
要並行運行for循環,只需在for
循環語句上方使用#pragma omp parallel for
,並且在for
循環外聲明的任何變量將由所有線程共享,而在for循環內聲明的任何變量對每個線程都是私有的。
請注意,如果並行執行文件IO,則可能不會看到太多的加速(如果您僅做文件IO,則幾乎沒有加速),除非至少有一些文件位於不同的物理硬盤驅動器上。
也許是這樣的(請注意,這只是一個草圖,我沒有驗證它,但是您可以理解):
// some X, M, N, Y, Z are some constant values
const int processes = 4;
std::vector<double> vct(X);
std::vector<std::vector<double> > stackVct(processes, std::vector<double>(Y));
std::vector<std::vector<std::string> > files(processes, M)
for(int i=0; i < N; ++i)
{
// parallel stuff
#pragma omp parallel firstprivate(vct, files) shared(stackVct)
{
#pragma omp for
for(int process = 0; process < processes; ++process)
{
std::vector<double> &otherVct = stackVct[process];
const std::vector<std::string> &my_files = files[process];
for(int file = 0; file < my_files.size(); ++file)
{
// vct is read-only here, the value is not modified
doSomeOtherStuff(otherVct, vct);
// my_files[file] is read-only
std::vector<double> thirdVct(Y);
doSomeOtherStuff(my_files[file], thirdVct(Y));
// thirdVct and vct are read-only
doSomeOtherStuff2(thirdVct, otherVct, vct);
}
}
// when all the parallel stuff is done, do this job
// single thread stuff
// stackVct is read-only, vct is modified
#pragma omp single nowait
doSingleTheadStuff(vct, stackVct)
}
}
vct
和files
標記為第一個私有files
,因為它們是只讀的,並且我假定不應對其進行修改,因此每個線程將為其自身獲取這些變量的副本。 stackVct
被標記為在所有線程之間共享,因為它們會對其進行修改。 doSingleTheadStuff
函數,而不會強制其他線程等待。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.