编写一个肯定会陷入死锁的程序 [英] Write a program that will surely go into deadlock

查看:18
本文介绍了编写一个肯定会陷入死锁的程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在一次采访中被问到这个问题.

I recently got this questions asked in an interview.

我回答说如果交错出错就会出现死锁,但是面试官坚持可以写一个不管交错都会死锁的程序.

I answered that deadlock occurs if the interleaving goes wrong, but the interviewer insisted that a program that will always go into deadlock regardless of interleaving can be written .

我们能写出这样的程序吗?你能指点我一些这样的示例程序吗?

Can we write such a program ? Can you point me to some example program like that ?

推荐答案

UPDATE: 这个问题是我 2013 年 1 月博客的主题.谢谢你的好问题!

UPDATE: This question was the subject of my blog in January 2013. Thanks for the great question!

我们如何编写一个无论线程如何调度都会陷入死锁的程序?

How can we write a program that will always go into deadlock no matter how the threads are scheduled?

这是一个 C# 示例.请注意,该程序似乎不包含锁,也没有共享数据.它只有一个局部变量和三个语句,但它 100% 肯定会死锁.人们很难想出一个更简单的程序,它肯定会死锁.

Here's an example in C#. Note that the program appears to contain no locks and no shared data. It has only a single local variable and three statements, and yet it deadlocks with 100% certainty. One would be hard-pressed to come up with a simpler program that deadlocks with certainty.

给读者练习#1:解释这个死锁是如何产生的.(答案在评论中.)

Exercise to the reader #1: explain how this deadlocks. (An answer is in the comments.)

读者练习 #2:演示 Java 中相同的死锁.(答案在这里:https://stackoverflow.com/a/9286697/88656)

Exercise to the reader #2: demonstrate the same deadlock in Java. (An answer is here: https://stackoverflow.com/a/9286697/88656)

class MyClass
{
  static MyClass() 
  {
    // Let's run the initialization on another thread!
    var thread = new System.Threading.Thread(Initialize);
    thread.Start();
    thread.Join();
  }

  static void Initialize() 
  { /* TODO: Add initialization code */ }

  static void Main() 
  { }
}

这篇关于编写一个肯定会陷入死锁的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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