/****************************************************************************
@File Name: test.cpp
@Author: wangzhicheng
@Created Time: Fri 17 Mar 2017 07:21:52 PM CST
****************************************************************************/
#include <iostream>
#include <string>
#include <vector>
#include <thread>
#include <mutex>
#include <chrono>
using namespace std;
static const string BLANK = " ";
struct Employee
{
string m_id;
vector<string>lunch_partners;
mutex m_lock;
Employee(const string &id):m_id(id)
{
}
void Output(string &strOut)
{
strOut = m_id;
strOut += " lunch parntners = ";
for(const auto &str:lunch_partners)
{
strOut += str;
strOut += BLANK;
}
}
};
void SendMail(const Employee &e0, const Employee &e1)
{
// e0 send mail to e1
this_thread::sleep_for(chrono::seconds(1));
}
void assign_lunch_partner(Employee &e0, Employee &e1)
{
if(&e0 == &e1) return;
// Locks the given Lockable objects lock1, lock2, ..., lockn using a deadlock avoidance algorithm to avoid deadlock
lock(e0.m_lock, e1.m_lock);
lock_guard<mutex>lk0(e0.m_lock, adopt_lock);
lock_guard<mutex>lk1(e1.m_lock, adopt_lock);
e0.lunch_partners.emplace_back(e1.m_id);
e1.lunch_partners.emplace_back(e0.m_id);
SendMail(e0, e1);
SendMail(e1, e0);
};
int main()
{
Employee e0("e0");
Employee e1("e1");
Employee e2("e2");
Employee e3("e3");
string str;
vector<thread>threads;
threads.emplace_back(assign_lunch_partner, ref(e0), ref(e1));
threads.emplace_back(assign_lunch_partner, ref(e0), ref(e2));
threads.emplace_back(assign_lunch_partner, ref(e0), ref(e3));
threads.emplace_back(assign_lunch_partner, ref(e1), ref(e2));
for(auto &th:threads)
{
th.join();
}
e0.Output(str);
cout << str << endl;
e1.Output(str);
cout << str << endl;
e2.Output(str);
cout << str << endl;
e3.Output(str);
cout << str << endl;
return 0;
}
deadlock avoidance
原创
©著作权归作者所有:来自51CTO博客作者我是006的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:openssl_aes
下一篇:sscanf
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章