死锁

当两个线程争夺两个互斥、独占的资源时很容易发生死锁。

根据这个原理可以用C#描绘出死锁的情况。

 

 

class Program

    {

        /// <summary>

        /// 连个资源对象

        /// </summary>

        static object res1 = new object ( );

        static object res2 = new object ( );

        /// <summary>

        /// 死锁标志

        /// </summary>

        public static int flag = 0;

 

        static void Main ( string [ ] args )

        {

           

            //启动两个线程进行资源竞争

            System. Threading. Thread t1 = new System. Threading. Thread ( Thread1 );

            System. Threading. Thread t2 = new System. Threading. Thread ( Thread2 );

 

            DateTime dt1 = DateTime. Now;

            t1. Start ( );

            t2. Start ( );

          

            while ( true )

            {

                int count = flag;

                System. Threading. Thread. Sleep ( 0 );

                //如果两个线程处于相斥阶段,则发生死锁。

                if ( count == flag )

                {

                    DateTime dt2 = DateTime. Now;

                    TimeSpan ts1 = new TimeSpan ( dt1. Ticks );

                    TimeSpan ts2 = new TimeSpan ( dt2. Ticks );

                    Console. WriteLine ( "哎,死锁啦!用时:"+ts2.Subtract(ts1).Duration().Milliseconds.ToString()+" 毫秒.");

                }

            }         

        }

        /// <summary>

        /// 先锁定”资源1“,然后是锁定 “资源2

        /// </summary>

        private static void Thread1 ( )

        {

            while ( true )

            {

                System. Threading. Monitor. Enter ( res2);

                System. Threading. Monitor. Enter ( res1);

 

                flag++;

 

                System. Threading. Monitor. Exit ( res1 );

                System. Threading. Monitor. Exit ( res2 );

            }

        }

        /// <summary>

        /// 先锁定”资源2“,然后是锁定 “资源1

        /// </summary>

        private static void Thread2 ( )

        {

            while ( true )

            {

                System. Threading. Monitor. Enter ( res1 );

                System. Threading. Monitor. Enter ( res2 );

 

                flag++;

 

                System. Threading. Monitor. Exit ( res2 );

                System. Threading. Monitor. Exit ( res1 );

            }

        }

    }

线程1锁定资源2,然后向获得资源1的锁,线程2正好相反。这时候就产生了死锁。

Monitor.TryEnter(,);

可以比较宽容的加锁在一定的时间段内。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值