Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::mutex::lock blocking CPU usage

I want to be able to freeze and unfreeze a thread at will.
My current solution is done through callbacks and busy waiting with sleep. This is obviously not an optimal solution.

I'm considering having the main thread lock a mutex, then have the slave thread run a function that locks and unlocks the same mutex.
My worry is the possible CPU usage if it's a true busy wait.
My question, as such, is: how does STL in C++11 specify "blocking", and if it is a busy wait, are there less CPU intensive solutions (e.g. pthreads)?


1 Answers

While mutexes can be used, it is not an optimal solution because mutexes should be used for resource protection (see also this q/a). Usually, std::condition_variable instances are what you should be looking for. It works as follows:

  1. Create an instance of std::condition_variable and distribute it to your controlling thread and your controlled thread
  2. In the controlled thread, create a std::unique_lock. Pass it to one of the condition variable's wait methods
  3. In the controlling thread, invoke one of the notify methods on the condition variable.

Hope that helps.

like image 113
J. D. Avatar answered Nov 21 '25 14:11

J. D.



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!