[英]std::lock_guard within openmp parallel
#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;
}
Hi, I can't understand the output of such code.嗨,我无法理解此类代码的 output。 Looks like that mutex is not unlocked after each loop.看起来每个循环后互斥锁都没有解锁。 But lock_guard is defined inside loop, isn't it?但是 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
My system is linux with g++ 9.1.0我的系统是 linux 和 g++ 9.1.0
Google is your friend.谷歌是你的朋友。 You can find documentation of std::lock_guard
at https://en.cppreference.com/w/cpp/thread/lock_guard您可以在https://en.cppreference.com/w/cpp/thread/lock_guard找到std::lock_guard
的文档
If you read it it explains how this works.如果您阅读它,它会解释这是如何工作的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.