What is Deadlock
In concurrent computing, a deadlock is a state in which each member of a group is waiting for another member, including itself, to take action, such as sending a message or more commonly releasing a lock.[1] Deadlock is a common problem in multiprocessing systems, parallel computing, and distributed systems, where software and hardware locks are used to arbitrate shared resources and implement process synchronization.[2]
In an operating system, a deadlock occurs when a process or thread enters a waiting state because a requested system resource is held by another waiting process, which in turn is waiting for another resource held by another waiting process. If a process is unable to change its state indefinitely because the resources requested by it are being used by another waiting process, then the system is said to be in a deadlock.[3]
In a communications system, deadlocks occur mainly due to lost or corrupt signals rather than resource contention.[4] --Wikipedia
死锁的一个比较专业的定义是:一组互相竞争资源的线程因互相等待,导致“永久”阻塞的现象。
关于这种现象,我们可以借助资源分配图来可视化锁的占用情况(资源分配图是个有向图,它可以描述资源和线程的状态)。其中,资源用方形节点表示,线程用圆形节点表示;资源中的点指向线程的边表示线程已经获得该资源,线程指向资源的边则表示线程请求资源,但尚未得到。发生死锁时的资源分配图就如下图所示,一个“各据山头死等”的尴尬局面。
发生死锁要如何解决
并发程序一旦死锁,一般没有特别好的方法,很多时候我们只能重启应用。
如何预防死锁
死锁的4个必要条件:
- 互斥,共享资源 X 和 Y 只能被一个线程占用;
- 占有且等待,线程 T1 已经取得共享资源 X,在等待共享资源 Y 的时候,不释放共享资源 X;
- 不可抢占,其他线程不能强行抢占线程 T1 占有的资源;
- 循环等待,线程 T1 等待线程 T2 占有的资源,线程 T2 等待线程 T1 占有的资源,就是循环等待。
只要我们破坏其中一个,就可以成功避免死锁的发生:
- 互斥
- 无解,因为我们用锁为的就是互斥。下一个
- 占有且等待
- 一次性申请所有的资源,这样就不存在等待了
- 不可抢占
- 占用部分资源的线程进一步申请其他资源时,如果申请不到,可以主动释放它占有的资源
- 循环等待
- 按序申请,是指资源是有线性顺序的,申请的时候可以先申请资源序号小的,再申请资源序号大的,这样线性化后自然就不存在循环了。