std::unique_lock<Mutex>::try_lock
来自 cppreference.cn
< cpp | thread | unique_lock
bool try_lock(); |
(C++11 起) | |
尝试锁定(即,获取)关联的互斥量而不阻塞。实际调用 mutex()->try_lock()。
如果没有关联的互斥量,或者互斥量已被此 std::unique_lock 锁定,则抛出 std::system_error。
目录 |
[编辑] 参数
(无)
[编辑] 返回值
如果成功获取互斥量的所有权,则为 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 互斥量,如果互斥量直到指定时间点仍不可用,则返回 (公共成员函数) | |
解锁(即释放)关联的互斥量 (公共成员函数) |