Do threads sleep when waiting on a locked mutex?

  • A+

Do threads blocked by a std::mutex::lock() or a condition variable sleep in a way that frees the core for other processes, or am I required to manually put these threads to sleep? And if true, would std::mutex::try_lock() allow for a way to spin the thread without sleeping?

The reason I ask: I want to have three states for threads in my thread pool that are unused: spinning for 2 milliseconds, then locked by a mutex for 250-ish milliseconds (assuming this lets them sleep and unhog the core), then finally being deallocated.

I want to avoid calling sleep manually if I can help it, tuning the sleep duration would be hard. So can I safely leave that to the mutex?


That is implementation specific; the C++ standard does not speak to it directly.

In practice, mutexes may use a combination of spin lock and full sleep. Sleeping and waking up is relatively expensive, and a compiler may write the locks to spin for a few ms before putting the thread to sleep.

No C++ implementation on a major phone, PC or big iron is going to spin lock indefinitely however. I could imagine some embedded system doing so, but have not personally encountered one.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: