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).
[[编辑]] 参见
锁定(即,取得关联互斥量的所有权) (public member function) | |
尝试锁定(即,取得关联的 TimedLockable 互斥量所有权),如果互斥量在指定的时间段内不可用则返回 (public member function) | |
尝试锁定(即,取得关联的 TimedLockable 互斥量所有权),如果互斥量在到达指定时间点之前一直不可用则返回 (public member function) | |
解锁(即,释放关联互斥量的所有权) (public member function) |