首页 > 代码库 > C++11多线程04

C++11多线程04

死锁

#include <iostream>
#include <thread>
#include <mutex>
#include <fstream>

class LofFile
{
public:

    void shared_print(std::string name , int num)
    {
        std::lock_guard<std::mutex> locker(m_mutex) ;
        std::lock_guard<std::mutex> locker2(m_mutex2) ;
        std::cout<<name<<": "<<num<<std::endl;
    }
    void shared_print2(std::string name , int num)
    {
        std::lock_guard<std::mutex> locker2(m_mutex2) ;
        std::lock_guard<std::mutex> locker(m_mutex) ;

        std::cout<<name<<": "<<num<<std::endl;
    }
private:
    std::mutex m_mutex ;
    std::mutex m_mutex2 ;
};

void thread_fun(LofFile& log)
{
    for(int i = 0 ; i>-100 ;i--)
    {
        log.shared_print("子线程",i);
    }
}

int main()
{
    LofFile log ;

    std::thread t(thread_fun,std::ref(log));

    for(int i=0 ;i<100;i++)
    {
        log.shared_print2("主线程",i);
    }

    t.join();

    return 0;
}

 

技术分享

解决死锁方法1:使mutex顺序相同

#include <iostream>
#include <thread>
#include <mutex>
#include <fstream>

class LofFile
{
public:

    void shared_print(std::string name , int num)
    {
        std::lock_guard<std::mutex> locker(m_mutex) ;
        std::lock_guard<std::mutex> locker2(m_mutex2) ;
        std::cout<<name<<": "<<num<<std::endl;
    }
    void shared_print2(std::string name , int num)
    {

        std::lock_guard<std::mutex> locker(m_mutex) ;
        std::lock_guard<std::mutex> locker2(m_mutex2) ;
        std::cout<<name<<": "<<num<<std::endl;
    }
private:
    std::mutex m_mutex ;
    std::mutex m_mutex2 ;
};

void thread_fun(LofFile& log)
{
    for(int i = 0 ; i>-100 ;i--)
    {
        log.shared_print("子线程",i);
    }
}

int main()
{
    LofFile log ;

    std::thread t(thread_fun,std::ref(log));

    for(int i=0 ;i<100;i++)
    {
        log.shared_print2("主线程",i);
    }

    t.join();

    return 0;
}

技术分享

解决死锁方法2:使用std::lock

#include <iostream>
#include <thread>
#include <mutex>
#include <fstream>

class LofFile
{
public:

    void shared_print(std::string name , int num)
    {
        std::lock(m_mutex,m_mutex2);
        std::lock_guard<std::mutex> locker(m_mutex,std::adopt_lock) ;
        std::lock_guard<std::mutex> locker2(m_mutex2,std::adopt_lock) ;
        std::cout<<name<<": "<<num<<std::endl;
    }
    void shared_print2(std::string name , int num)
    {
        std::lock(m_mutex,m_mutex2);
        std::lock_guard<std::mutex> locker2(m_mutex2,std::adopt_lock) ;
        std::lock_guard<std::mutex> locker(m_mutex,std::adopt_lock) ;

        std::cout<<name<<": "<<num<<std::endl;
    }
private:
    std::mutex m_mutex ;
    std::mutex m_mutex2 ;
};

void thread_fun(LofFile& log)
{
    for(int i = 0 ; i>-100 ;i--)
    {
        log.shared_print("子线程",i);
    }
}

int main()
{
    LofFile log ;

    std::thread t(thread_fun,std::ref(log));

    for(int i=0 ;i<100;i++)
    {
        log.shared_print2("主线程",i);
    }

    t.join();

    return 0;
}

技术分享

 

C++11多线程04