gpt4 book ai didi

c++ - 线程安全堆栈 C++ 中的潜在死锁

转载 作者:行者123 更新时间:2023-12-01 14:18:27 26 4
gpt4 key购买 nike

在“Concurrency in Action”一书中,有一个线程安全堆栈的实现,其中在进入 pop() 和 empty() 函数时获取/锁定互斥锁,如下所示:

class threadsafe_stack {
private:
std::stack<T> data;
mutable std::mutex m;
public:
//...
void pop(T& value) {
std::lock_guard<std::mutex> lock(m);
if(data.empty()) throw empty_stack();
value = std::move(data.top());
data.pop();
}

bool empty() const {
std::lock_guard<std::mutex> lock(m);
return data.empty();
}
};

我的问题是,当进入 pop() 时获取锁的线程调用也受互斥锁保护的 empty() 时,这段代码如何不会陷入死锁?如果 lock() 被已经拥有互斥锁的线程调用,那不是未定义的行为吗?

最佳答案

how does this code not run into a deadlock, when a thread, that has acquired the lock upon entering pop() is calling empty() which is protected by mutex as well?



因为你不是在打电话 empty threadsafe_stack的成员函数但是您正在调用类 std::stack<T> 的 empty() .如果代码是:
void pop(T& value) 
{
std::lock_guard<std::mutex> lock(m);
if(empty()) // instead of data.empty()
throw empty_stack();
value = std::move(data.top());
data.pop();
}

那么,它将是 undefined behavior :

If lock is called by a thread that already owns the mutex, the behavior is undefined: for example, the program may deadlock. An implementation that can detect the invalid usage is encouraged to throw a std::system_error with error condition resource_deadlock_would_occur instead of deadlocking.



了解 recursiveshared互斥体。

关于c++ - 线程安全堆栈 C++ 中的潜在死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61587582/

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