我正在考虑使用以下代码:
auto now = std::chrono::high_resolution_clock::now();
std::unique_lock<std::mutex> lock(mutex, std::defer_lock);
if(lock.try_lock_until(now + std::chrono::milliseconds(15))
{
// swap some buffer pointers...
lock.unlock();
}
但是,从文档中我不清楚 try_lock_until()
是否实现为繁忙等待,或者线程是否会在尝试之间屈服/ sleep (这是我想要的行为)。这是查询锁同时最小化线程资源使用的最佳方法吗?
最佳答案
CppReference page for std::unique_lock::try_lock_until
实际上只声明它“阻塞直到达到指定的 timeout_time
或获取锁”。但这不仅仅是该网站的缺点。标准(我使用 the November 2014 working draft )小心地避开指定是否 thread
必须yield
阻止任何类型的 mutex
,仅讨论获取所有权。
对于std::mutex
,例如,第 30.4.1.2.1 节规定
If one thread owns a
mutex
object, attempts by another thread to acquire ownership of that object will fail (fortry_lock()
) or block (forlock()
) until the owning thread has released ownership with a call to unlock().
没有提及日程安排或 yield
不过, ing 确实是制作出来的。
此外,即使它确实提到了 yield
明确地说,这没有多大帮助,如 this_thread::yield
(第 30.3.2 节)仅仅是“为实现提供重新安排时间的机会”。
CppReference使这一点更加具体,指出
The exact behavior of this function depends on the implementation, in particular on the mechanics of the OS scheduler in use and the state of the system. For example, a first-in-first-out realtime scheduler (SCHED_FIFO in Linux) would suspend the current thread and put it on the back of the queue of the same-priority threads that are ready to run (and if there are no other threads at the same priority, yield has no effect).
所以我担心如何try_lock_until
的问题无法回答用C++实现。也许您可以针对特定平台提出一个新问题。对于你的第二个问题(“这是在最小化线程资源使用的同时查询锁的最佳方式吗?”),答案是肯定的,你的平台提供的最佳选项应该使用此 API 来调用(不过,正如 T.C. 评论的那样,try_lock_for
似乎更合适)。
关于c++ - std::unique_lock::try_lock_until() 是否忙等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31750036/