user2138149
user2138149

Reputation: 17120

C++ std::scoped_lock: What happens if the lock blocks?

I am interested to know more about how the std::scoped_lock operates.

I am making some modifications to some thread-unsafe code by adding a mutex around a critical section.

I am using a std::scoped_lock to do this.

There are two possible things which can happen when the line of code std::scoped_lock lock(mutex) is reached:

  1. The mutex is locked successfully. Nothing to be concerned with here.

  2. The mutex is being held by another thread (A). The mutex cannot be locked, and presumably the current thread (B) blocks.

Regarding point 2, what happens when the thread which was able to lock the mutex unlocks it again? ie: When thread A unlocks the mutex (scoped_lock goes out of scope) what does thread B do? Does it automatically wake up and try to lock the mutex again? (Does thread B sleep when it is not able to lock the mutex? Presumably it does not sit in an infinite while(1) like loop hogging the CPU.)

As you can see I don't have a complete understanding of how a scoped_lock works. Is anyone able to enlighten me?

Upvotes: 1

Views: 2133

Answers (1)

MSalters
MSalters

Reputation: 179961

Your basic assumptions are pretty much correct - block, don't hog the CPU too much (a bit is OK), and let the implementation deal with thread wake-ups.

There's one special case that should be mentioned: when a mutex is used not just to protect a shared resource, but specifically to coordinate between threads A&B, a std::condition_variable can help with the thread synchronization. This does not replace the mutex; in fact you need to lock a mutex in order to wait on a condition variable. Many Operating Systems can benefit from condition variables by waking up the right threads faster.

Upvotes: 2

Related Questions