在操作系统中,死锁是很敏感的问题,很多意外的发生和死锁有着直接的关系,而死锁产生的原因有大概四种,我想了想,与其从如何解决死锁开始学习死锁,不如从制造死锁开始学习死锁.以下是我利用Monitor.Enter()制造的第一种死锁情况:

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;


class Program
{
    static void Main(string[] args)
    {
        Add add1 = new Add ();
        Thread thread1 = new Thread (new ThreadStart (add1 .ThreadProc));
        Thread thread2 = new Thread(new ThreadStart(add1.ThreadProc));
        thread1.Start();
        thread2.Start();
        thread1.Join();
        thread2.Join();
        Console.WriteLine(add1.Result);
        Console.ReadLine();

    }
}

class Add
{
    protected int a = 0;
    protected void Update()
    {
        Monitor.Enter(this);
        a++;
    }
    public int Result
    {
        get
        {
            return a;
        }
    }
    public void ThreadProc()
    {
        for (int n = 0; n < 10; n++)
        {
            Update();
        }
    }
}

原理其实很简单,就是在进程thread1进行时占用a的使用权(通过Monitor.Enter(this)实现),然后故意不使用Monitor.Exit(this)释放使用权,这样,进程thread2在进行时需要使用a,但是,由于a已经进入了Monitor类的保护区,造成进程thread2无法访问,必须等待的状况,而同时,由于缺少了Monitor.Exit()的实现,a的使用权是不会被释放的,进程thread2一直等待,造成了死锁deadlock.

posted on 2008-01-17 16:35  肖斌  阅读(393)  评论(1编辑  收藏  举报