c++的单线程 mutex 问题

查看 63|回复 3
作者:Attenton   
今天在学习std::recursive_mutex的时候看到std::recursive_mutex的应用场景是可重入申请锁,于是写了代码进行测试,确实在循环调用的时候不会出现死锁了。之后又用mutex进行了测试,但是发现在不同场景下会有不同的情况,代码如下:
#include [i]
#include
std::recursive_mutex recursive_mutex_;
std::mutex mutex_;
void func(int n) {
    std::lock_guard lock(mutex_);
    std::cout  0) {
        func(n - 1);
    }
}
int main() {
    func(5);
    return 0;
}
按照预期,以上代码应该在打印了 5 之后就一直卡主,可是在 gcc 7.5 下,直接打印了 5 4 3 2 1 ;测试了很多在线编译器都是这个现象,只有https://www.onlinegdb.com/online_c++_compiler 这个在线编译器的运行结果符合预期。
请问各位大佬,这个现象的原因是什么?
应该不是 lock_guard 的问题,因为我自己手写了 lock_guard 查看了 lock 的声明周期,确实是在 func 执行结束之后才 unlock 。

std, mutex, func, lock_guard

Attenton
OP
  
补充:CmakeLists.txt 里面没有添加任何编译选项,cmake 版本是 3.18 , 用的 c++ 17
iwdmb   
~/Project/C/testtest$ g++ --version
g++ (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
~/Project/C/testtest$ ./a.out
n = 5
Attenton
OP
  
@iwdmb
(base) root@ubuntu:/home# ./a.out
n = 5
n = 4
n = 3
n = 2
n = 1
n = 0
(base) root@ubuntu:/home# g++ --version
g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
以上是我的执行结果,没搞懂是哪的问题
您需要登录后才可以回帖 登录 | 立即注册

返回顶部