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

标签 c++ multithreading

下面的代码有什么问题?我只是尝试设置一个非常简单的线程安全堆栈,当我运行多个线程并发地在堆栈上进行压入和弹出时,有时会报告 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/

相关文章:

C++ 使用函数参数类型进行模板参数推导

C++ 作业队列 : Is there a rule of thumb for the number of worker threads?

c++ - 不存在编译警告(GCC 和 g++)

c++ - PostThreadMessage 到另一个进程

c++ - 将 bool 转换为位域中的位

c++ - 如何在 C++ 中正确使用嵌套类?

multithreading - 以 Node Js 方式创建工作队列的正确方法?

java - 获取当前在 Java 中运行的所有线程的列表

multithreading - 在 Kotlin Native 中,如何将对象保存在单独的线程中,并在不使用 C 指针的情况下从任何其他线程中改变其状态?

objective-c - 如何在 Objective-C 中等待线程完成