Namespaces
Variants

std::unique_lock<Mutex>:: try_lock

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
bool try_lock ( ) ;
(C++11 이후)

연관된 뮤텍스를 블로킹 없이 잠그려고 시도합니다(즉, 소유권을 획득합니다). 효과적으로 mutex ( ) - > try_lock ( ) 를 호출합니다.

std::system_error 는 연결된 뮤텍스가 없거나 뮤텍스가 이미 이 std::unique_lock 에 의해 잠겨 있는 경우 발생합니다.

목차

매개변수

(없음)

반환값

true 뮤텍스의 소유권을 성공적으로 획득한 경우, false 그렇지 않은 경우.

예외

  • mutex ( ) - > try_lock ( ) 에 의해 발생하는 모든 예외 ( Mutex 타입은 try_lock 에서 예외를 던지지 않지만, 사용자 정의 Lockable 은 예외를 던질 수 있음).

예제

다음 예제들은 잠금 및 잠금 해제된 뮤텍스를 획득하려고 시도합니다.

#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)