Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does blocked thread incur performance penalty?

I have a method that needs access to a static array and do some heavy calculation.

public void DoIt(){
  lock(myStaticArray){
    // do crazy stuff
  }
}

The method takes one or two seconds to complete so some nano seconds to acquire lock is of no importance here.

Now assume 10 threads reach the code and one entered. Now does it make the running code inside the thread slower than if no thread was waiting for the lock? Do the blocked threads waiting for lock cost any CPU usage while waiting?

like image 960
morteza khosravi Avatar asked Dec 07 '25 10:12

morteza khosravi


1 Answers

The simple answer is no, there is no appreciable CPU impact to the running thread (the one doing "crazy stuff") due to other threads waiting on the lock.

As mentioned in the comments, the threads will probably spin wait ("busy wait", where they are using CPU time) for a very short while, which will take a certain very negligible amount of CPU time, then they will go into a wait state, which means that they will not be scheduled on the CPU until the object that they are waiting on is signaled (meaning the thread doing work leaves the lock).

like image 90
Chris Shain Avatar answered Dec 10 '25 00:12

Chris Shain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!