在线文档教程
C++
线程支持 | Thread support

std::timed_mutex::try_lock_for

STD::定时[医]互斥::尝试[医]锁[医]为

template< class Rep, class Period > bool try_lock_for( const std::chrono::duration& timeout_duration (since C++11)

试图锁定互斥体。块,直到指定timeout_duration已过或已取得锁,以第一位为准。关于成功锁定获取返回true,否则返回false...

如果timeout_duration小于或等于timeout_duration.zero(),该函数的行为类似于try_lock()...

用一个稳定的时钟来测量持续时间。此函数的阻塞时间可能超过timeout_duration由于调度或资源争用延迟。

和...一样try_lock(),则允许此函数伪造失败并返回。false期间,即使互斥锁没有被任何其他线程锁定。timeout_duration...

优先unlock()对同一个互斥体的操作同步性中定义的28名ASstd::memory_order%29如果返回此操作true...

如果try_lock_for由已经拥有mutex,该行为是未定义的。

参数

timeout_duration-maximum duration to block for

返回值

true如果成功获取锁,则为false...

例外

任何由时钟、时间引发的异常[医]在执行%28时钟、时间点和标准库提供的持续时间期间,不要抛出%29。

二次

#include <iostream> #include <mutex> #include <thread> #include <vector> #include <sstream> std::mutex cout_mutex; // control access to std::cout std::timed_mutex mutex; void job(int id) { using Ms = std::chrono::milliseconds; std::ostringstream stream; for (int i = 0; i < 3; ++i) { if (mutex.try_lock_for(Ms(100))) { stream << "success "; std::this_thread::sleep_for(Ms(100) mutex.unlock( } else { stream << "failed "; } std::this_thread::sleep_for(Ms(100) } std::lock_guard<std::mutex> lock(cout_mutex std::cout << "[" << id << "] " << stream.str() << "\n"; } int main() { std::vector<std::thread> threads; for (int i = 0; i < 4; ++i) { threads.emplace_back(job, i } for (auto& i: threads) { i.join( } }

二次

可能的产出:

二次

[0] failed failed failed [3] failed failed success [2] failed success failed [1] success failed success

二次

另见

locklocks the mutex, blocks if the mutex is not available (public member function)
try_locktries to lock the mutex, returns if the mutex is not available (public member function)
try_lock_untiltries to lock the mutex, returns if the mutex has beenunavailable until specified time point has been reached (public member function)
unlockunlocks the mutex (public member function)

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cppreference.com/w/cpp/线程/timeed[医]互斥/尝试[医]锁[医]为