你对这个锁的问题?你对、问题

2023-09-04 03:12:00 作者:呐放肆的青春°

高度有这锁一个问题,但我不明白那是什么。我有强烈的怀疑下面的例子不锁不够好。那么有什么方法可以问题?

 类的例子
{
    对象更衣室=新的对象();
    无效的start()
    {
        的for(int i = 0; I< 1000;我++)
        {
            (新主题(dostuff))启动();
        }
    }
    无效dostuff()
    {
        锁(更衣室)
        {
            //做一点事
        }
    }
}
 

解决方案

您code创建1000线程。这是极其昂贵的,需要超过1 GB的内存。

解锁新的面试技巧 回答你有哪些缺点

和那么所有这些线程争夺一个锁,基本上serialzing(DE线程)的整个操作。

但是,你的锁定的正常工作,没有什么不对劲的地方。只是,当您运行此的应用程序的它可能看起来像你的电脑崩溃。

另外请注意,您要保护的对象应与1对1的更衣室对象。

但对于一个更好的答案,你必须张贴code就是有点更加完整,也许更接近真实的东西。

Highly there is a problem in this lock but i couldn't understand what is that. I have strong suspicious that below example doesn't lock enough well. So what can be problem ?

class example
{
    object locker = new object();
    void start()
    {
        for (int i = 0; i < 1000; i++)
        {
            (new Thread(dostuff)).Start();
        }
    }
    void dostuff()
    {
        lock (locker)
        {
            //dosomething
        }
    }
}

解决方案

Your code creates 1000 Threads. That is enormously expensive, requiring over 1 GB of memory.

And then all those threads compete for a single lock, essentially serialzing (de-threading) the whole operation.

But your lock works fine, nothing wrong there. It's just that when you run this application it might look like your PC is crashing.

Also note that the object you are trying to protect should be tied 1-on-1 with the locker object.

But for a better answer you'll have to post code that is a little more complete and maybe closer to the real thing.