gpt4 book ai didi

c++ - 我的简单线程安全堆栈有什么问题?

转载 作者:搜寻专家 更新时间:2023-10-30 23:55:46 24 4
gpt4 key购买 nike

下面的代码有什么问题?我只是尝试设置一个非常简单的线程安全堆栈,当我运行多个线程并发地在堆栈上进行压入和弹出时,有时会报告 0xC0000005 异常。

#include <stack>
#include <list>
#include <memory>
#include <mutex>


template<class T> class Stack{
typedef stack < shared_ptr<T>, list<shared_ptr<T>>> Stack_;
public:
Stack(){}
Stack(const Stack& other){
lock_guard<mutex>(other.mtx_);
stack_ = other.stack_;
}
void push(shared_ptr<T> value){
lock_guard<mutex>(this->mtx_);
stack_.push(value);
}
shared_ptr<T> pop(){
lock_guard<mutex>(this->mtx_);
if (stack_.empty()) return nullptr;
auto res = stack_.top();
stack_.pop();
return res;
}
private:
mutex mtx_;
Stack_ stack_;
};

最佳答案

我看到的主要问题是您没有正确锁定资源。

这个:

lock_guard<mutex>(this->mtx_); // temporary

它会在您锁定后立即解锁,因为它是临时的并且只存在到 ;

你应该像这样创建一个命名变量:

lock_guard<mutex> lock(this->mtx_); // lives till end of scope

参见: This Post有关临时对象的信息。

关于c++ - 我的简单线程安全堆栈有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30379987/

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