How to explain the “deadlock” better?

前端 未结 15 1004
不知归路
不知归路 2020-12-13 00:52

I am struggling to explain \"deadlock\" in threads in easy words, so please help. What could be the best example of \"deadlock\" (say, in Java), and how it does happen in st

15条回答
  •  死守一世寂寞
    2020-12-13 01:24

    I'd rather explain it in terms totally unrelated to computers since that's often the best way to get an idea across.

    I have a five-year-old son and a three-year-old daughter. Both want to do the same colouring-in book.

    The daughter grabs the pencils while the son grabs the book. Neither will relinquish what they have until they get the other.

    That's deadlock. It doesn't get any simpler than that.

    Your processes (or children) are stuck waiting for each other and will continue waiting indefinitely until some other superior process (like Dad) comes in and breaks the deadlock.

    At least with the children, you can (sometimes) get one of them to see reason and relinquish their lock. This is not usually possible with computers since the processes are not doing anything except waiting for that resource (although sometimes children enter this state as well).

    Following one rule will guarantee that deadlock cannot occur:

    • Have all threads of execution allocate resources in the same order.

    Following some extra rules will make your threads less likely to slow each other down but keep in mind that the above rule should take precedence over all others:

    • Allocate resources only when you need them.
    • Release them as soon as you're finished with them.

提交回复
热议问题