微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

linux – 锁定C 11 std :: unique_lock会导致死锁异常

我正在尝试使用C 11 std :: condition_variable,但是当我尝试从第二个线程锁定与之关联的unique_lock时,我得到一个异常“资源死锁避免”.创建它的线程可以锁定和解锁它,但不能锁定和解锁它,即使我非常确定在第二个线程试图锁定它时不应该锁定unique_lock.

FWIW我在Linux中使用gcc 4.8.1 -std = gnu 11.

我已经在condition_variable,unique_lock和mutex周围写了一个包装类,所以我的代码中没有其他东西可以直接访问它们.注意使用std :: defer_lock,我已经陷入了陷阱:-).

class Cond {
private:
    std::condition_variable cCond;
    std::mutex cMutex;
    std::unique_lock<std::mutex> cULock;
public:
    Cond() : cULock(cMutex,std::defer_lock)
    {}

    void wait()
    {
        std::ostringstream id;
        id << std::this_thread::get_id();
        H_LOG_D("Cond %p waiting in thread %s",this,id.str().c_str());
        cCond.wait(cULock);
        H_LOG_D("Cond %p woke up in thread %s",id.str().c_str());
    }

    // Returns false on timeout
    bool waitTimeout(unsigned int ms)
    {
        std::ostringstream id;
        id << std::this_thread::get_id();
        H_LOG_D("Cond %p waiting (timed) in thread %s",id.str().c_str());
        bool result = cCond.wait_for(cULock,std::chrono::milliseconds(ms))
                == std::cv_status::no_timeout;
        H_LOG_D("Cond %p woke up in thread %s",id.str().c_str());
        return result;
    }

    void notify()
    {
        cCond.notify_one();
    }

    void notifyAll()
    {
        cCond.notify_all();
    }

    void lock()
    {
        std::ostringstream id;
        id << std::this_thread::get_id();
        H_LOG_D("Locking Cond %p in thread %s",id.str().c_str());
        cULock.lock();
    }

    void release()
    {
        std::ostringstream id;
        id << std::this_thread::get_id();
        H_LOG_D("Releasing Cond %p in thread %s",id.str().c_str());
        cULock.unlock();
    }
};

我的主线程创建了一个RenderContext,它有一个与之关联的线程.从主线程的角度来看,它使用Cond来通知渲染线程执行操作,并且还可以在COnd上等待渲染线程完成该操作.渲染线程在Cond上等待主线程发送渲染请求,并使用相同的Cond告诉主线程它在必要时完成了一个动作.当渲染线程试图锁定Cond来检查/等待渲染请求时,我会得到错误,此时它根本不应该被锁定(因为主线程在等待它),更不用说了相同的线程.这是输出

DEBUG: Created window
DEBUG: OpenGL 3.0 Mesa 9.1.4,GLSL 1.30
DEBUG: setScreen locking from thread 140564696819520
DEBUG: Locking Cond 0x13ec1e0 in thread 140564696819520
DEBUG: Releasing Cond 0x13ec1e0 in thread 140564696819520
DEBUG: Entering GLFW main loop
DEBUG: requestRender locking from thread 140564696819520
DEBUG: Locking Cond 0x13ec1e0 in thread 140564696819520
DEBUG: requestRender waiting
DEBUG: Cond 0x13ec1e0 waiting in thread 140564696819520
DEBUG: Running thread 'RenderThread' with id 140564575180544
DEBUG: render thread::run locking from thread 140564575180544
DEBUG: Locking Cond 0x13ec1e0 in thread 140564575180544
terminate called after throwing an instance of 'std::system_error'
  what():  Resource deadlock avoided

说实话,我真的不明白unique_lock是什么,为什么condition_variable需要一个而不是直接使用互斥锁,所以这可能是问题的原因.我在网上找不到合适的解释.

解决方法

前言:用条件变量理解一个重要的事情是它们可能会受到随机的,虚假的唤醒.换句话说,CV可以从wait()退出,而没有任何人首先调用notify _ *().不幸的是,没有办法区分这种假的唤醒与合法的唤醒,因此唯一的解决方案是拥有一个额外的资源(至少是一个布尔值),以便你可以判断是否真的满足了唤醒条件.

这个额外的资源也应该由互斥锁保护,通常与您作为CV的伴侣一样使用.

CV /互斥对的典型用法如下:

std::mutex mutex;
std::condition_variable cv;
Resource resource;

void produce() {
    // note how the lock only protects the resource,not the notify() call
    // in practice this makes little difference,you just get to release the
    // lock a bit earlier which slightly improves concurrency
    {
        std::lock_guard<std::mutex> lock(mutex); // use the lightweight lock_guard
        make_ready(resource);
    }
    // the point is: notify_*() don't require a locked mutex
    cv.notify_one(); // or notify_all()
}

void consume() {
    std::unique_lock<std::mutex> lock(mutex);
    while (!is_ready(resource))
        cv.wait(lock);
    // note how the lock still protects the resource,in order to exclude other threads
    use(resource);
}

与您的代码相比,请注意多个线程如何同时调用produce()/ consume()而不必担心共享的unique_lock:唯一的共享内容是mutex / cv / resource,每个线程都有自己的unique_lock,迫使线程等待它如果互斥锁已被其他东西锁定,则转动.

正如您所看到的,资源无法真正与CV /互斥体对分离,这就是为什么我在评论中说你的包装类不适合恕我直言,因为它确实试图将它们分开.

通常的方法是不要像你想要的那样为CV /互斥对创建一个包装器,而是为整个CV /互斥/资源三重奏.例如.一个线程安全的消息队列,消费者线程将在CV上等待,直到队列准备好消耗消息.

如果你真的只想包装CV /互斥对,你应该摆脱不安全的lock()/ release()方法(从RAII的角度来看)并用一个lock()方法替换它们返回一个的unique_ptr:

std::unique_ptr<std::mutex> lock() {
    return std::unique_ptr<std::mutex>(cMutex);
}

这样你可以使用你的Cond包装类,就像我上面展示的那样:

Cond cond;
Resource resource;

void produce() {
    {
        auto lock = cond.lock();
        make_ready(resource);
    }
    cond.notify(); // or notifyAll()
}

void consume() {
    auto lock = cond.lock();
    while (!is_ready(resource))
        cond.wait(lock);
    use(resource);
}

但说实话,我不确定这是值得的:如果你想使用recursive_mutex而不是普通的互斥锁怎么办?好吧,你必须从你的类中创建一个模板,以便你可以选择互斥类型(或者一共编写第二个类,yay代码重复).无论如何,你不会获得太多收益,因为你仍然需要编写几乎相同的代码来管理资源.仅适用于CV /互斥体对的包装器类太薄了包装器才真正有用恕我直言.但像往常一样,YMMV.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐