为什么这个锁语句不起作用? [英] why doesn't this lock statement work?

查看:79
本文介绍了为什么这个锁语句不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Program
{
    static object test = new object();
    static void Main(string[] args)
    {
        new Program().test2();
        Console.ReadKey();
    }

    public void test1()
    {
        lock (test)
        {
            Console.WriteLine("test1");
        }
    }

    public void test2()
    {
        lock (test)
        {
            test1();
            Console.WriteLine("test2");
        }
    }
}

上面的代码是否应该首先在test2()的lock语句中完成语句,然后转到test1()? (即输出不应该是这样的吗?: 测试2 测试1 )

Is the code above supposed to first finish statements in lock statement of test2() then go to the test1()? (i.e. Doesn't the output supposed to be like this? : test2 test1 )

推荐答案

监视器在同一线程上是可重入.为避免意外的死锁,这一点非常重要,如果没有这种行为,您的代码将被牢固地冻结.

A monitor is re-entrant on the same thread. Pretty important to avoid accidental dead-lock, your code would freeze solidly if it didn't have that behavior.

互斥体也是可重入的,信号量则不是.

A Mutex is also re-entrant, a Semaphore is not.

实现非常简单.监视器存储两条信息.输入该线程的线程的所有者Thread.ManagedId和一个计数器,该计数器对输入该线程的次数进行计数.因此第一个锁可以进入,因为它不归它所有,它将所有者设置为您的线程,并将计数设置为1.第二个锁被允许输入,因为线程ID匹配,计数增加为2.第二次锁定时,计数再次递减为1.在第一个结尾处,计数递减为0,这将重置所有者.

The implementation is pretty straight forward. A Monitor stores two pieces of information. The owner Thread.ManagedId of the thread that entered it and a counter that counts the number of times it was entered. So the first lock can enter since it isn't owned, it sets the owner to your thread and the count to 1. The second lock is allowed to enter since the thread ID matches, the count increments to 2. At the end of the second lock, the count decrements to 1 again. At the end of the first, the count decrements to 0 and that resets the owner.

这篇关于为什么这个锁语句不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆