一、单线程死锁
void b();
void a()
{
mutex m;
m.lock();
b();
cout<<"a\n";
m.unlock();
}
void b()
{
mutex m2;
m2.lock();
a();
cout<<"b\n";
m2.unlock();
}
int main()
{
a();
}
函数a调用b,而b又调用a,造成死锁。
二、多线程死锁
mutex G_m;
condition_variable G_cv;
bool f1=true,f2=true;
void b();
void a()
{
for (int i = 0; i < 100; ++i)
{
unique_lock<mutex> locker(G_m);
G_cv.wait(locker,[]{ return f1;});
Sleep(10);cout<<"a\n";
f2=true;
f1=false;
}
}
void b()
{
for (int i = 0; i < 100; ++i)
{
unique_lock<mutex> locker(G_m);
G_cv.wait(locker, [] { return f2; });
Sleep(100); cout << "b\n";
f1 = true;
f2=false;
}
}
int main()
{
thread t(a);
thread t2(b);
t.join();
t2.join();
}
当两个线程同时将f1、f2置为false,则两个函数都等待对方将f1、f2置为true,导致死锁
三、智能指针死锁
class B;
class A
{
shared_ptr<B> p;
public:
void _set(shared_ptr<B> b){ p=b;}
~A() { cout << "A\n"; }
};
class B
{
shared_ptr<A> p;
public:
void _set(shared_ptr<A> a){ p=a;}
~B() { cout << "~B\n"; }
};
void sisuo()
{
shared_ptr<A> a = make_shared<A>();
shared_ptr<B> b = make_shared<B>();
a->_set(b);
b->_set(a);
}
int main()
{
sisuo();
cout<<"a";
}
两个对象中的智能指针互相指向对方,导致无法正常调用析构函数。