应用场景:当该线程条件不满足,处于等待资源的状态的时候,我们希望他等待的时候不浪费CPU资源,那么应该这么处理。 (写线程池的时候,需要考虑的情况)
void function()
{
while (True)
{
if (!HasTask())
{
// we should use this_thread::yield() here.
return;
}
// else
// {
// // do work
// }
}
}
源码参照: https://github.com/facebook/folly/blob/a3e8938068d849312e828da0ebb39973696cdcca/folly/synchronization/LifoSem.h#L427
/// Prevents blocking on this semaphore, causing all blocking wait()
/// calls to throw ShutdownSemError. Both currently blocked wait() and
/// future calls to wait() for which tryWait() would return false will
/// cause an exception. Calls to wait() for which the matching post()
/// has already occurred will proceed normally.
void shutdown() {
// first set the shutdown bit
auto h = head_->load(std::memory_order_acquire);
while (!h.isShutdown()) {
if (h.isLocked()) {
std::this_thread::yield();
h = head_->load(std::memory_order_acquire);
continue;
}
if (head_->compare_exchange_strong(h, h.withShutdown())) {
// success
h = h.withShutdown();
break;
}
// compare_exchange_strong rereads h, retry
}
...
}
void sleep_for( const std::chrono::duration<Rep, Period>& sleep_duration );
阻塞至少sleep_duration时间,由于调度或资源争用延迟,该函数可能会阻塞超过 sleep_duration 的时间。