编写一个肯定会进入死锁的程序 [英] Write a program that will surely go into deadlock
问题描述
我最近在面试中遇到了这个问题。
我回答说,如果交错错误,就会发生死锁,但是访问者坚持认为程序总是会进入死锁而不管交织是否可以写。
我们可以写这样的程序吗?你能指点我这样的示例程序吗?
更新:这个问题是我的博客在2013年1月的主题。非常感谢您提出的问题!
我们如何编写一个程序
这是C#中的一个例子。请注意,该程序似乎不包含锁定和共享数据。它只有一个局部变量和三个语句,但它的死锁有100%的确定性。
练习读者#1:解释一下死锁。 (答案在注释中。)
练习读者#2:在Java中演示同样的死锁。 (答案在这里: http://stackoverflow.com/a/9286697/88656 )
class MyClass
{
static MyClass()
{
//让我们在另一个线!
var thread = new System.Threading.Thread(Initialize);
thread.Start();
thread.Join();
}
static void Initialize()
{/ * TODO:添加初始化代码* /}
static void Main()
{}
}
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: 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?
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.
Exercise to the reader #1: explain how this deadlocks. (An answer is in the comments.)
Exercise to the reader #2: demonstrate the same deadlock in Java. (An answer is here: http://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屋!