std::unique_lock<Mutex>::try_lock
来自 cppreference.com
< cpp | thread | unique lock
bool try_lock(); |
(自 C++11 起) | |
尝试锁定(即获取)关联的互斥体,而不阻塞。实际上调用 mutex()->try_lock().
std::system_error 如果没有关联的互斥体,或者如果互斥体已被此 std::unique_lock 锁定,则抛出。
内容 |
[编辑] 参数
(无)
[编辑] 返回值
true 如果已成功获取互斥体的所有权,否则为 false.
[编辑] 异常
- 如果没有关联的互斥体,则为 std::system_error,错误代码为 std::errc::operation_not_permitted.
- 如果互斥体已被此
std::unique_lock
锁定,则为 std::system_error,错误代码为 std::errc::resource_deadlock_would_occur.
[编辑] 示例
以下示例尝试获取一个已被锁定和解锁的互斥体。
运行此代码
#include <chrono> #include <iostream> #include <mutex> #include <thread> #include <vector> using namespace std::chrono_literals; int main() { std::mutex counter_mutex; std::vector<std::thread> threads; using Id = int; auto worker_task = [&](Id id, std::chrono::seconds wait, std::chrono::seconds acquire) { // wait for a few seconds before acquiring lock. std::this_thread::sleep_for(wait); std::unique_lock<std::mutex> lock(counter_mutex, std::defer_lock); if (lock.try_lock()) std::cout << '#' << id << ", lock acquired.\n"; else { std::cout << '#' << id << ", failed acquiring lock.\n"; return; } // keep the lock for a while. std::this_thread::sleep_for(acquire); std::cout << '#' << id << ", releasing lock (via destructor).\n"; }; threads.emplace_back(worker_task, Id{0}, 0s, 2s); threads.emplace_back(worker_task, Id{1}, 1s, 0s); threads.emplace_back(worker_task, Id{2}, 3s, 0s); for (auto& thread : threads) thread.join(); }
输出
#0, lock acquired. #1, failed acquiring lock. #0, releasing lock (via destructor). #2, lock acquired. #2, releasing lock (via destructor).
[编辑] 另请参阅
锁定(即获取)关联的互斥体 (公共成员函数) | |
尝试锁定(即获取)关联的 TimedLockable 互斥体,如果互斥体在指定的时间段内一直不可用,则返回 (公共成员函数) | |
尝试锁定(即获取)关联的 TimedLockable 互斥体,如果互斥体在指定的时间点到达之前一直不可用,则返回 (公共成员函数) | |
解锁(即释放)关联的互斥体 (公共成员函数) |