Sun Studio 12:线程分析器用户指南

3.2.1 哲人怎样发生死锁

当每个哲人都持有他自己的筷子并等待邻座的筷子变为可用时,会发生实际死锁:

哲人 0 持有筷子 0,但等待筷子 1 

哲人 1 持有筷子 1,但等待筷子 2 

哲人 2 持有筷子 2,但等待筷子 3 

哲人 3 持有筷子 3,但等待筷子 4 

哲人 4 持有筷子 4,但等待筷子 0 

在这种情况下,没有人可以吃,这些哲人处于死锁状态。多次重新运行该程序,您将看到该程序可能有时挂起,或有时运行直到完成。

运行哲人进餐程序,并查看它完成还是发生死锁。它可能挂起,如以下样例运行所示:

prompt% cc din_phil.c -mt
prompt% a.out
Philosopher 0 is done thinking and now ready to eat.
Philosopher 2 is done thinking and now ready to eat.
Philosopher 2: got right  chopstick 2
Philosopher 2: got left chopstick 3
Philosopher 0: got right  chopstick 0
Philosopher 0: got left chopstick 1
Philosopher 0: eating.
Philosopher 4 is done thinking and now ready to eat.
Philosopher 4: got right  chopstick 4
Philosopher 2: eating.
Philosopher 3 is done thinking and now ready to eat.
Philosopher 1 is done thinking and now ready to eat.
Philosopher 0: got right  chopstick 0
Philosopher 3: got right  chopstick 3
Philosopher 2: got right  chopstick 2
Philosopher 1: got right  chopstick 1
(hang)

Execution terminated by pressing CTRL-C