c++死锁模拟与检测

 死锁在并发编程里面是很难预防的,锁和线程比较少的情况下还能通过分析代码,理出线索进行避免,一旦超过一定数量感觉就会无从下手,必须通过自动化工具进行检测。以下示例对哲学家就餐问题进行模拟,动态构建线程依赖拓扑图,并用Floyd - Warshall找环算法,找寻死锁链,在程序运行过程中如果死锁链成型,将会清晰地给出锁链信息,对下一步的死锁解除提供有力指导依据。

#include <thread>
#include <chrono>
#include <mutex>
#include <condition_variable>
#include <string>
#include <set>
#include <map>
#include <iostream>

#define STRINGIFY(s) #s
#define TOSTRING(s) STRINGIFY(s)
#define _CONCATE_(x,y) __FILE__##x##y
#define CONCATE(x,y) _CONCATE_(x,y)
#define LOCKNAME CONCATE(":",TOSTRING(__LINE__))

#define LOCK_INIT() {LOCKNAME, new std::mutex}

typedef struct _lock_t
{
    std::mutex* mutex;
    const char* name;
    std::thread::id tid;
    _lock_t() :_lock_t(nullptr, nullptr) {}
    _lock_t(const char* _name, std::mutex* mtx) :name(_name), mutex(mtx) {}
    _lock_t(_lock_t&& lk)
    {
        this->mutex = lk.mutex;
        this->name = lk.name;
        lk.mutex = nu
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值