首页>Program>source

有人可以举一个例子说明如何用C#语言引起线程死锁吗?

最新回答
  • 2天前
    1 #

    static object object1 = new object();
    static object object2 = new object();
    public static void ObliviousFunction()
    {
        lock (object1)
        {
            Thread.Sleep(1000); // Wait for the blind to lead
            lock (object2)
            {
            }
        }
    }
    public static void BlindFunction()
    {
        lock (object2)
        {
            Thread.Sleep(1000); // Wait for oblivion
            lock (object1)
            {
            }
        }
    }
    static void Main()
    {
        Thread thread1 = new Thread((ThreadStart)ObliviousFunction);
        Thread thread2 = new Thread((ThreadStart)BlindFunction);
        thread1.Start();
        thread2.Start();
        while (true)
        {
            // Stare at the two threads in deadlock.
        }
    }
    

  • 2天前
    2 #

    来自C#中的线程

    At the other end of the scale, separate synchronization contexts invite deadlocks. Here's an example:

    [Synchronization]
    public class Deadlock : ContextBoundObject {
        public DeadLock Other;
        public void Demo() { Thread.Sleep (1000); Other.Hello(); }
        void Hello() { Console.WriteLine ("hello"); }
    }
    public class Test {
        static void Main() {
        Deadlock dead1 = new Deadlock();
        Deadlock dead2 = new Deadlock();
        dead1.Other = dead2;
        dead2.Other = dead1;
        new Thread (dead1.Demo).Start();
        dead2.Demo();
    }
    

    Because each instance of Deadlock is created within Test – an unsynchronized class – each instance will gets its own synchronization context, and hence, its own lock. When the two objects call upon each other, it doesn't take long for the deadlock to occur (one second, to be precise!) The problem would be particularly insidious if the Deadlock and Test classes were written by different programming teams. It may be unreasonable to expect those responsible for the Test class to be even aware of their transgression, let alone know how to go about resolving it. This is in contrast to explicit locks, where deadlocks are usually more obvious.

  • ios:iOS8:可以为静态单元格使用" tableviewrowHeight = UITableViewAutomaticDimension"吗?
  • ajax:如果用户在页面加载完成之前离开页面,则触发jQuery ajaxError()处理程序