开发者

What is problem on this lock?

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 probl开发者_开发知识库em ?

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


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.


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.


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...)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜