简体   繁体   English

在等待锁定的互斥锁时线程是否会睡眠?

[英]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? std::mutex::lock()或条件变量阻塞的线程是否以释放其他进程的核心的方式休眠,或者我是否需要手动将这些线程置于休眠状态? And if true, would std::mutex::try_lock() allow for a way to spin the thread without sleeping? 如果是真的, std::mutex::try_lock()允许一种在没有睡眠的情况下旋转线程的方法?

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. 我问的原因是:我希望线程池中的线程有三种状态未使用:旋转2毫秒,然后由互斥锁锁定250毫秒(假设这让他们睡觉并取消核心),最后被解除分配。

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. C ++标准没有直接对它说话。

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. 然而,在主要手机,PC或大型主机上没有C ++实现无限期地旋转锁定。 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. 这种被阻塞的线程会休眠并且不会占用任何CPU周期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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