std::unique_lock<Mutex>::try_lock
來自 cppreference.com
< 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 互斥量,如果互斥量直到指定時間點仍不可用,則返回 (公共成員函式) | |
解鎖(即釋放)關聯的互斥量 (公共成員函式) |