Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bottleneck in Threads C++

So I am just trying to verify my understanding and hope that you guys will be able to clear up any misunderstandings. So essentially I have two threads which use the same lock and perform calculations when they hold the lock but the interesting thing is that within the lock I will cause the thread to sleep for a short time. For both threads, this sleep time will be slightly different for either thread. Because of the way locks work, wont the faster thread be bottlenecked by the slower thread as it will have to wait for it to complete?

For example:

Thread1() {

   lock();
   usleep(10)
   lock();

}

-

Thread2() {

   lock();
   sleep(100)
   lock();

}

Now because Thread2 holds onto the lock longer, this will cause a bottleneck. And just to be sure, this system should have a back and forth happens on who gets the lock, right?

It should be:

Thread1 gets lock
Thread1 releases lock
Thread2 gets lock
Thread2 releases lock
Thread1 gets lock
Thread1 releases lock
Thread2 gets lock
Thread2 releases lock

and so on, right? Thread1 should never be able to acquire the lock right after it releases it, can it?

like image 792
QQCompi Avatar asked Apr 27 '26 20:04

QQCompi


1 Answers

Thread1 should never be able to acquire the lock right after it releases it, can it?

No, Thread1 could reacquire the lock, right after it releases it, because Thread2 could still be suspended (sleeps because of the scheduler)

Also sleep only guarantees that the thread will sleep at least the wanted amount, it can and will often be more.

In practice you would not hold a lock while calculating a value, you would get the lock, get the needed values for calculation, unlock, calculate it, and then get the lock again, check if the old values for the calculation are still valid/wanted, and then store/return your calculated results. For this purpose, the std::future and atomic data types were invented.

...this system should have a back and forth happens on who gets the lock, right?

Mostly The most of the time it will be a back and forth but some times there could/will be two lock/unlock cycles by Thread1. It depends on your scheduler and any execution and cycle will probably vary.

like image 93
Superlokkus Avatar answered Apr 30 '26 12:04

Superlokkus



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!