How to explain the “deadlock” better?

前端 未结 15 918
不知归路
不知归路 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:06

    Guffa's description is good.

    The best way I've found to avoid deadlocks is to only lock around resources that are private to you, and to release the lock before you call anything that you do not have exclusive control over.

    The only problem is that this may require you to shift from using locks for maintaing consistency to using compensating actions, but it's probably less likely to cause problems in the long run, anyway.

    This article is good to read about this problem.

    0 讨论(0)
  • 2020-12-13 01:09

    Dining philosophers - you have 4 people sitting at a table, and 4 chopsticks. You need 2 chopsticks to eat. Imagine each philosopher tries to eat as follows:

    1. Pick up left chopstick.
    2. Pick up right chopstick.
    3. Eat.
    4. Set right chopstick back.
    5. Set left chopstick back.

    Everyone does step 1. Now step 2 is impossible, since each person waits for the one on his right to drop the left, which they won't do. This is deadlock. If they just took turns then they could all eat, but instead they all starve.

    0 讨论(0)
  • 2020-12-13 01:11

    Usually the classes of concurrent programming explains deadlock by examples. I think that the problem of the Dining Philosophers will be a good example to use. You can develop this example in Java and explain the occurrence of deadlock when two philosophers holds a left fork and are waiting for the right fork. (or vice versa).

    I learned a lot of concepts from concurrent programming using this examples implemented on Java.

    0 讨论(0)
  • 2020-12-13 01:13

    Imagine you and your girlfriend quarrelled over who should open the door in order to leave the house.The person who apologises will open the door. She is waiting for you to apologise, you are waiting for her to apologise which results in the couple never leaving the house as both refuse to apologise.

    0 讨论(0)
  • 2020-12-13 01:14

    Deadlock happens when you have 2 different resources that 2 different threads need to lock in order to use them. The threads lock them in the opposite order, so it becomes impossible for execution to continue until 1 of the threads backs down.

    Wikipedia has a couple good real-life examples of deadlock.

    0 讨论(0)
  • 2020-12-13 01:14

    Sample1:

    I promised never do promises

    Sample2:

    Talking with genie of the lamp: My wish is that you never make wishes comes true

    Sample3:

    recruiter: I will hire you if you explain deadlock.

    candidate: If you hire me I will explain what deadlock is about

    0 讨论(0)
提交回复
热议问题