简体   繁体   中英

Do threads sleep when waiting on a locked mutex?

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.

Yes. Such blocked threads sleep and don't take up any CPU cycles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM