deadlock avoidance

本文介绍了一个使用C++标准库中的线程和互斥锁来避免死锁的示例程序。该程序演示了如何为员工分配午餐伙伴,并通过发送电子邮件通知他们。通过使用std::lock确保了在更新员工的午餐伙伴列表时不会发生竞态条件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/****************************************************************************
@File Name: test.cpp
@Author: wangzhicheng
@mail: 2363702560@qq.com
@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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值