c++ - std::lock_guard 在 openmp 并行

标签 c++ locking openmp

#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/

相关文章:

locking - 更新 Redis 键/值时获取锁

c++ - 内存泄漏 - OpenMP

c++ - 在C语言中使用遗传算法求一个数的平方根时如何实现选择和交叉

c++ - C++中无库分类SVM的实现

c++ - 父进程的父进程 ID - Linux

mysql - 行级锁定在 rails/mysql 中无法按预期工作

c++ - 有没有人尝试过 C++ 的事务内存?

c++ - 如何有条件地终止 OpenMP 中的并行区域?

linux - 长时间运行时程序停顿

c++ - std::string 中的 Malloc 错误