你对这个锁的问题? [英] What is problem on this lock?

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

问题描述

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

 类的例子
{
    对象更衣室=新的对象();
    无效的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.

这篇关于你对这个锁的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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