c++ - std::lock_guard<std::mutex> 施工段错误?

标签 c++ c++11 segmentation-fault mutex

我正在尝试使用 std::mutex 和 std::lock_guard 访问共享的 std::queue。 mutex (pending_md_mtx_) 是另一个对象(其地址有效)的成员变量。我的代码似乎在 lock_guard 的构造上出现了段错误。

有什么想法吗?我应该改用 std::unique_lock (或其他对象)吗?在 Ubuntu Linux 下运行 GCC 4.6 (--std=c++0x)。我无法发布整个类(class),但只能访问下面列出的互斥锁和队列。

template <typename ListenerT>
class Driver
{
public:
    template <typename... Args>
    Driver(Args&&... args) :
        listener_(std::forward<Args>(args)...) {}

    void enqueue_md(netw::Packet* packet)
    {
        std::lock_guard<std::mutex> lock(pending_md_mtx_);
        pending_md_.push(packet);
    }

    void process_md()
    {
        std::lock_guard<std::mutex> lock(pending_md_mtx_);
        while (pending_md_.size())
        {
            netw::Packet* pkt=pending_md_.front();
            pending_md_.pop();
            process_md(*pkt);
        }
    }
    //... Other code which I can't post...

private:
    ListenerT listener_;
    std::mutex pending_md_mtx_;
    std::queue<netw::Packet*> pending_md_;
};

GDB 堆栈跟踪:

(gdb) bt
#0  __pthread_mutex_lock (mutex=0x2f20aa75e6f4000) at pthread_mutex_lock.c:50
#1  0x000000000041a2dc in __gthread_mutex_lock (__mutex=0xff282ceacb40) at /usr/include/c++/4.6/x86_64-linux-gnu/./bits/gthr-default.h:742
#2  lock (this=0xff282ceacb40) at /usr/include/c++/4.6/mutex:90
#3  lock_guard (__m=..., this=0x7f2874fc4db0) at /usr/include/c++/4.6/mutex:445
#4  driver::Driver<Listener, false>::enqueue_md (this=0xff282ceac8a0, packet=...) at exec/../../driver/Driver.hpp:95

最佳答案

我在构建 std::lock_guard 时遇到段错误,结果我的代码使用了一个未初始化的 std::shared_ptr<my_object_with_mutex> .使用正确构建的 my_object_with_mutex解决问题。

关于c++ - std::lock_guard<std::mutex> 施工段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18366594/

相关文章:

c - 使用指针而不是索引更新数组

C++、Mac OS X、Xcode 8 : Compile Boost : Set deployment target to OS X 10. 11

c++ - 传递给 C++ 函数的数组大小?

c++ - 从文件中读取空格分隔的数字直到换行符

c++ - push_backs 到 std::vector<std::reference_wrapper<type>>

c++ - 嵌套的 if-else 不适用于自定义结构 c++

c++ - 枚举指针可以指向常量值吗?

c++ - 为什么这个顶点缓冲对象更新失败?

c++ - 具有默认参数的函数<void(T)> 参数

c - 指针&字符段错误