What is the problem with this lock?

There is a problem with this lock, but I could not understand what it is. I have a strong suspicion that the example below is not blocking well enough. So what could be the 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
        }
    }
}
+2
source share
4 answers

Your code creates 1000 threads. It is extremely expensive, requiring more than 1 GB of memory.

And then all these threads compete for one lock, essentially serializing (de-threading) the whole operation.

But your castle is working fine, there is nothing to worry about. It’s just that when you run this application it may seem like your computer is crashing.


Also note that the object you are trying to protect must be bound 1 to 1 with the locker object.

, , , .

+3

, 1000 , . , ( ) , .

, dostuff() for.

+4

, , 1000 . .

"dostuff" . , ( ...)

+2

, : 1000 , .

The only problem you may encounter in locking is if you need to execute the code only one at a time, regardless of the number of copies of the created class. If this is important, you need to make a static object-locker.

+2
source

All Articles