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

标签 c++ multithreading c++11 locking

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

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 (for try_lock()) or block (for lock()) 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/

相关文章:

c++ - 我如何将 std::pair 声明为 friend 以便它看到私有(private)默认构造函数

C++类实例化和内部调用方法

java - 多线程快速排序比预期慢很多

c# - 使用 await 和 async 在 long 方法运行时释放 UI 线程

c++ - std::function 到对象的成员函数和对象的生命周期

c++ - 仅使用递归来提取c++中 vector 中的最大元素

c++ - 在 C++ 中从父文件夹的父文件夹提供文件位置

java - 线程连接自身

c++ - 如何将std::function类型分配给sigevent.sigev_notify_function(POSIX计时器)

c++ - 天真的把 C++ 翻译成 Julia,有优化的空间吗?