user1241335
user1241335

Reputation:

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

Upvotes: 3

Views: 3535

Answers (2)

J. D.
J. D.

Reputation: 113

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.

Upvotes: 3

Liam M
Liam M

Reputation: 5432

Have a look at this answer: Multithreading, when to yield versus sleep. Locking a mutex (in the manner you've described), is a reasonable solution to your problem.

Here's an MSDN article that's worth a read. Quote:

Until threads that are suspended or blocked become ready to run, the scheduler does not allocate any processor time to them, regardless of their priority.

If a thread isn't being scheduled it's not being run.

Upvotes: 1

Related Questions