Namespaces
Variants

std::shared_lock<Mutex>:: try_lock_for

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
template < class Rep, class Period >
bool try_lock_for ( const std:: chrono :: duration < Rep,Period > & timeout_duration ) ;
(C++14 起)

尝试以共享模式锁定关联的互斥量。阻塞直到指定的 timeout_duration 时间耗尽或成功获取锁(以先到者为准)。成功获取锁时返回 true ,否则返回 false 。实际等效调用 mutex ( ) - > try_lock_shared_for ( timeout_duration )

该函数可能因调度或资源竞争延迟而阻塞超过 timeout_duration 时长。

标准建议使用稳定时钟来测量持续时间。如果实现使用系统时钟替代,等待时间也可能对时钟调整敏感。

std::system_error 会在没有关联互斥锁或互斥锁已被锁定时抛出。

Mutex 不满足 SharedTimedLockable 要求,则行为未定义。

目录

参数

timeout_duration - 阻塞等待的最长持续时间

返回值

true 表示已成功获取互斥锁的所有权, false 表示获取失败。

异常

  • mutex ( ) - > try_lock_shared_for ( timeout_duration ) 抛出的任何异常。

示例

参见

尝试锁定(即获取所有权)关联的 TimedLockable 互斥量,若互斥量在指定时长内不可用则返回
( std::unique_lock<Mutex> 的公开成员函数)
锁定关联的互斥量
(公开成员函数)
尝试锁定关联的互斥量
(公开成员函数)
尝试锁定关联的互斥量,直到指定时间点
(公开成员函数)
解锁关联的互斥量
(公开成员函数)