gpt4 book ai didi

c++ - 为什么第一个代码不会导致死锁

转载 作者:行者123 更新时间:2023-12-05 01:03:55 27 4
gpt4 key购买 nike

#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <thread>
std::mutex mtx;

void func2() {
mtx.lock();
std::cout << "here is 2" << std::endl;
mtx.unlock();
}

void func1() {
mtx.lock();
std::cout << "here is 1" << std::endl;
func2();
mtx.unlock();
}

int main() {
func1();
}

但是如果我修改main func如下,就会导致死锁

int main() {
std::thread t1(func1);
t1.join();
}

我通过“g++ test.cpp -std=c++11 -lpthread”同时满足了这两个要求

最佳答案

在同一个线程中调用 lock 两次(没有解锁互斥锁)是未定义的。来自 cppreference :

If lock is called by a thread that already owns the mutex, the behavior is undefined: for example, the program may deadlock.

它可能会死锁。或者它可能不会。行为未定义。

请注意 std::recursive_mutex可以被锁定多次(尽管只有一些未指定的限制)。但是,需要递归互斥锁的代码更复杂。在您的示例中,从 func1 中删除锁定会更容易,因为它仅在互斥锁已被锁定时调用。总的来说没那么简单。

关于c++ - 为什么第一个代码不会导致死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73135404/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com