#include <iostream>
#include <omp.h>
#include <mutex>
using namespace std;
int main()
{
mutex l;
#pragma omp parallel for
for(int i=0;i<24;i++){
int thread_num = omp_get_thread_num();
std::lock_guard<std::mutex> lg(l);
cout<<"i: "<<i<<" thread_num:"<<thread_num<<endl;
}
return 0;
}
您好,我无法理解此类代码的输出。看起来互斥量在每次循环后都没有解锁。但是 lock_guard 是在循环内部定义的,不是吗?
i: 0 thread_num:0
i: 1 thread_num:0
i: 2 thread_num:0
i: 3 thread_num:0
i: 4 thread_num:0
i: 5 thread_num:0
i: 12 thread_num:2
i: 13 thread_num:2
i: 14 thread_num:2
i: 15 thread_num:2
i: 16 thread_num:2
i: 17 thread_num:2
i: 6 thread_num:1
i: 7 thread_num:1
i: 8 thread_num:1
i: 9 thread_num:1
i: 10 thread_num:1
i: 11 thread_num:1
i: 18 thread_num:3
i: 19 thread_num:3
i: 20 thread_num:3
i: 21 thread_num:3
i: 22 thread_num:3
i: 23 thread_num:3
我的系统是带有 g++ 9.1.0 的 linux
最佳答案
Google 是您的 friend 。您可以在 https://en.cppreference.com/w/cpp/thread/lock_guard 找到 std::lock_guard
的文档
如果您阅读它,它会解释这是如何工作的。
关于c++ - std::lock_guard 在 openmp 并行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58514470/