gpt4 book ai didi

c++ - std::unique_lock::try_lock_until() 忙等待吗?

转载 作者:行者123 更新时间:2023-11-30 03:50:29 38 4
gpt4 key购买 nike

我正在考虑使用以下代码:

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() 被实现为忙等待,或者线程是否会在两次尝试之间产生/休眠(这是我想要的行为),我从文档中不清楚。这是在最小化线程资源使用的同时查询锁的最佳方式吗?

最佳答案

CppReference page for std::unique_lock::try_lock_until实际上只声明它“在达到指定的 timeout_time 或获取锁之前一直阻塞”。这不仅仅是网站的缺点。标准(我使用了 the November 2014 working draft )小心地避免指定 thread 在阻塞任何类型的 mutex 时是否必须 yield,说话仅关于获得所有权。

对于 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 (for try_lock()) or block (for lock()) until the owning thread has released ownership with a call to unlock().

不过,根本没有提及调度或 yielding。

此外,即使它确实明确提到了 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/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com