死锁在并发编程里面是很难预防的,锁和线程比较少的情况下还能通过分析代码,理出线索进行避免,一旦超过一定数量感觉就会无从下手,必须通过自动化工具进行检测。以下示例对哲学家就餐问题进行模拟,动态构建线程依赖拓扑图,并用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