第四章 死锁

来源:互联网 发布:王思聪雪梨的淘宝店铺 编辑:程序博客网 时间:2024/05/16 19:12

2多个资源的情况

  

  

#include<iostream>

#include<string>

#include<thread>

#include<mutex>

#include<fstream>

  

using namespace std;

  

std::mutex mu;

class lofFile

{

public:

lofFile()

{

f.open("log.txt");//构造函数中打开log.txt文件

}

void share_Print(std::string id, int value)

{

std::lock_guard<std::mutex> locker(m_mutex);

std::lock_guard<std::mutex> locker1(m_mutex1);

//std::lock_guard<mutex> locker(m_mutex);

std::cout<< "from " << id << value << endl;

}

void share_Print1(std::string id, int value)

{

std::lock_guard<std::mutex> locker1(m_mutex1);//注意此处的顺序

std::lock_guard<std::mutex> locker(m_mutex);

  

//std::lock_guard<mutex> locker(m_mutex);

std::cout<< "from " << id << value << endl;

}

protected:

private:

mutex m_mutex;

mutex m_mutex1;

ofstream f; //m_mutex保护的对象

};

  

void function_1(lofFile& l)

{

for (int i = 0; i > -100; i--)

{

//std::cout << "From t1:" << i << std::endl;

//using shared_Print function instead of function_1

l.share_Print("From t1", i);

  

}

}

int main()

{

lofFile l;

thread t1(function_1, std::ref(l));

for (int i = 0; i < 100; i++)

{

//cout << "From main:" << i << endl;

l.share_Print1("From Main()", i);

}

t1.join();

}

  

输出的结果:

  

  

显示出来并没有全部打出来,这是如果主线程和此线程都在等待彼此unlock,主线程使用完m_mutex1后,此时此线程也使用完m_mutex,主线程在等m_mutex,而次线程等待m_mutex1,从而产生死锁。

解决的方法有下面的方式:

std::lock_guard<std::mutex> locker1(m_mutex1);//注意此处的顺序

std::lock_guard<std::mutex> locker(m_mutex);

两个线程的顺序保持一致。或者使用std::lock()

Std::lock(m_mutex1,m_mutex);

//…….接下来的可以不按照顺序

#include<iostream>

#include<string>

#include<thread>

#include<mutex>

#include<fstream>

  

using namespace std;

  

std::mutex mu;

class lofFile

{

public:

lofFile()

{

f.open("log.txt");//构造函数中打开log.txt文件

}

void share_Print(std::string id, int value)

{

std::lock(m_mutex,m_mutex1);

std::lock_guard<std::mutex> locker(m_mutex,std::adopt_lock);//注意此处

std::lock_guard<std::mutex> locker1(m_mutex1,std::adopt_lock);

//std::lock_guard<mutex> locker(m_mutex);

std::cout<< "from " << id << value << endl;

}

void share_Print1(std::string id, int value)

{

std::lock(m_mutex, m_mutex1);

std::lock_guard<std::mutex> locker1(m_mutex1,std::adopt_lock);//注意此处的顺序

std::lock_guard<std::mutex> locker(m_mutex,std::adopt_lock);

  

//std::lock_guard<mutex> locker(m_mutex);

std::cout<< "from " << id << value << endl;

}

protected:

private:

mutex m_mutex;

mutex m_mutex1;

ofstream f; //m_mutex保护的对象

};

  

void function_1(lofFile& l)

{

for (int i = 0; i > -100; i--)

{

//std::cout << "From t1:" << i << std::endl;

//using shared_Print function instead of function_1

l.share_Print("From t1", i);

  

}

}

int main()

{

lofFile l;

thread t1(function_1, std::ref(l));

for (int i = 0; i < 100; i++)

{

//cout << "From main:" << i << endl;

l.share_Print1("From Main()", i);

}

t1.join();

}

  

  

0 0