What is problem on this lock?

淺唱寂寞╮ 提交于 2019-12-10 11:08:10

问题


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
        }
    }
}

回答1:


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.




回答2:


It looks like you're spinning up 1000 threads, then locking each one. That means that the code within dostuff (that lives in the lock section) will execute sequentially instead of at the same time.

As written, it would be more efficient to just call dostuff() directly in the for loop.




回答3:


I'm not quite sure what you are doing here, but your 1000 threads will run serially. Defeats the purpose of threads in the first place.

Your "dostuff" method immediate locks for the entire length of the thread run. The thread then unlocks, which the next thread in line can begin processing (and locks...)




回答4:


I'm not sure what your issue is-- this code will start dostuff 1000 times, but the code within the lock will only execute one at a time.

The only problem you might have with the lock is if you need to execute the code only one at a time regardless of the number of copies of the example class you have created. If this is important, then you need to make the locker object static.



来源:https://stackoverflow.com/questions/3462613/what-is-problem-on-this-lock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!