T
Tony Johansson
Hi!
Here I have some code that could cause deadlock
I have tried to force a deadlock from this program but I can't the only
thing that I have noticed is that sometimes it take a time before the First
and Second is written to the Console screen.
So I have two qestions.
1. Is there perhaps some automatic release when a deadlock has been detected
by the OS or .NET.
I mean if I perhaps get a deadlock when the first and second didn't were
written immediately but the deadlock was release automatically.
2. If I didn't get a deadlock after 50 attempts it seems to be very rare to
get. I mean you could get it some time but you never know when.
using System;
using System.Threading;
class Deadlocker
{
object ResourceA = new object();
object ResourceB = new object();
public void First()
{
lock(ResourceA)
{
lock (ResourceB)
{
Console.WriteLine("First");
}
}
}
public void Second()
{
lock (ResourceB)
{
lock (ResourceA)
{
Console.WriteLine("Second");
}
}
}
}
class Test
{
public static void Main()
{
Deadlocker deallock = new Deadlocker();
ThreadStart firstStart = new ThreadStart(deallock.First);
ThreadStart secondStart = new ThreadStart(deallock.Second);
Thread first = new Thread(firstStart);
Thread second = new Thread(secondStart);
first.Start();
second.Start();
first.Join();
second.Join();
Console.ReadLine();
}
}
Here I have some code that could cause deadlock
I have tried to force a deadlock from this program but I can't the only
thing that I have noticed is that sometimes it take a time before the First
and Second is written to the Console screen.
So I have two qestions.
1. Is there perhaps some automatic release when a deadlock has been detected
by the OS or .NET.
I mean if I perhaps get a deadlock when the first and second didn't were
written immediately but the deadlock was release automatically.
2. If I didn't get a deadlock after 50 attempts it seems to be very rare to
get. I mean you could get it some time but you never know when.
using System;
using System.Threading;
class Deadlocker
{
object ResourceA = new object();
object ResourceB = new object();
public void First()
{
lock(ResourceA)
{
lock (ResourceB)
{
Console.WriteLine("First");
}
}
}
public void Second()
{
lock (ResourceB)
{
lock (ResourceA)
{
Console.WriteLine("Second");
}
}
}
}
class Test
{
public static void Main()
{
Deadlocker deallock = new Deadlocker();
ThreadStart firstStart = new ThreadStart(deallock.First);
ThreadStart secondStart = new ThreadStart(deallock.Second);
Thread first = new Thread(firstStart);
Thread second = new Thread(secondStart);
first.Start();
second.Start();
first.Join();
second.Join();
Console.ReadLine();
}
}