简单的死锁示例 [英] Simple Deadlock Examples

查看:72
本文介绍了简单的死锁示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向新手解释线程死锁.过去,我看到过很多死锁的示例,有些使用代码,有些使用插图(例如著名的餐饮哲学家,但是对于真正的新手来说,这些问题可能太复杂而无法完全掌握.

I would like to explain threading deadlocks to newbies. I have seen many examples for deadlocks in the past, some using code and some using illustrations (like the famous 4 cars). There are also classic easily-deadlocked problems like The Dining Philosophers, but these may be too complex for a real newbie to fully grasp.

我正在寻找最简单的代码示例来说明什么是死锁.该示例应:

I'm looking for the simplest code example to illustrate what deadlocks are. The example should:

  1. 与某种意义上的真实"编程场景有关
  2. 简短,简单明了

您推荐什么?

推荐答案

也许是一个简单的银行情况.

Maybe a simple bank situation.

class Account {
  double balance;

  void withdraw(double amount){
     balance -= amount;
  } 

  void deposit(double amount){
     balance += amount;
  } 

   void transfer(Account from, Account to, double amount){
        sync(from);
        sync(to);

        from.withdraw(amount);
        to.deposit(amount);

        release(to);
        release(from);
    }

}

显然,如果有两个线程试图同时运行transfer( a,b )和transfer( b,a ),则死锁是之所以会发生,是因为他们试图以相反的顺序获取资源.

Obviously, should there be two threads which attempt to run transfer(a, b) and transfer(b, a) at the same time, then a deadlock is going to occur because they try to acquire the resources in reverse order.

此代码也非常适合查看死锁的解决方案.希望这会有所帮助!

This code is also great for looking at solutions to the deadlock as well. Hope this helps!

这篇关于简单的死锁示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆