c++11の死锁(deadlock)

一、死锁的产生

死锁的原因有两个

a、mutex的lock正确执行了,但是使用资源的时候发生了异常,导致unlock虽然调用了,但是没有执行,也就没有解锁

b、多把锁

两个mutex的时候,mutex1,mutex2

如果两把锁两个线程的顺序不一致,会造成相互等待释放资源,造成死锁

二、死锁的避免

1、是否需要两把以上的锁,如果不用两把锁,自然不会存在这个问题

2、锁的顺序一致,两个线程中调用的顺序一致(一般判断锁的地址大小)

      mutex1,mutex2 都是

3、使用std::lock_lockguard()可以解决没有正常调用unlock造成的死锁(实际就是一层封装,mutex析构的时候调用unlock)

 class LogfFile
{
public:
    LogfFile() {
        f.open("log.txt");
    }
    void share_print(std::string msg, int id)
    {
        std::lock(m_mutex1, m_mutex2);
        std::lock_guard<std::mutex> guard(m_mutex1,std::adopt_lock);
        std::lock_guard<std::mutex> guard(m_mutex2, std::adopt_lock);
        cout<< msg << id << endl;

    }
    void share_print2(std::string msg, int id)
    {
        std::lock_guard<std::mutex> guard(m_mutex1, std::adopt_lock);
        std::lock_guard<std::mutex> guard(m_mutex2, std::adopt_lock);
        cout << msg << id << endl;

    }

private:
    std::mutex m_mutex1, m_mutex2;
    std::ofstream f;
};

 

多线程一----多线程的应用

多线程二----简单线程管理

多线程三----数据竞争和互斥对象

多线程四----死锁和防止死锁

多线程五----unick_lock和once_flag

多线程六----条件变量

多线程七----线程间通信

posted @ 2019-02-28 14:33  卖雨伞的小男孩  阅读(955)  评论(0编辑  收藏  举报