Namespaces
Variants

std::recursive_timed_mutex:: try_lock_for

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
template < class Rep, class Period >
bool try_lock_for ( const std:: chrono :: duration < Rep, Period > & timeout_duration ) ;
(C++11 이후)

뮤텍스를 잠그려 시도합니다. 지정된 시간 timeout_duration 이 경과(타임아웃)하거나 락이 획득될 때까지(뮤텍스 소유) 블록합니다. 어느 것이 먼저 발생하든지 상관없습니다. 락 획득에 성공하면 true 를 반환하고, 그렇지 않으면 false 를 반환합니다.

만약 timeout_duration timeout_duration. zero ( ) 보다 작거나 같으면, 이 함수는 try_lock() 처럼 동작합니다.

이 함수는 스케줄링 또는 자원 경합 지연으로 인해 timeout_duration 보다 더 오랫동안 블록될 수 있습니다.

표준은 지속 시간을 측정하기 위해 std::steady_clock 을 사용할 것을 권장합니다. 구현이 대신 std::system_clock 을 사용하는 경우, 대기 시간이 시계 조정에도 영향을 받을 수 있습니다.

try_lock() 와 마찬가지로, 이 함수는 허위 실패(spurious failure)가 발생할 수 있으며 false 를 반환할 수 있습니다. 이는 timeout_duration 동안 일부 시점에 뮤텍스가 다른 스레드에 의해 잠겨 있지 않은 경우에도 발생할 수 있습니다.

동일한 뮤텍스에서 이전 unlock() 연산은 이 연산이 true 를 반환할 경우 synchronizes-with (다음에서 정의됨: std::memory_order ) 관계를 형성합니다.

스레드는 재귀적 뮤텍스에서 try_lock_for 를 반복적으로 호출할 수 있습니다. try_lock_for 호출이 성공할 때마다 소유권 카운트가 증가합니다: 뮤텍스는 스레드가 unlock() 을 해당 횟수만큼 호출한 후에만 해제됩니다.

소유권의 최대 계층 수는 명시되어 있지 않습니다. 이 수를 초과할 경우 try_lock_for 호출은 false 를 반환합니다.

목차

매개변수

timeout_duration - 최소 대기 시간

반환값

true 락이 성공적으로 획득된 경우, 그렇지 않으면 false .

예외

timeout_duration 에 의해 발생하는 모든 예외 (표준 라이브러리에서 제공하는 지속 시간은 절대 예외를 발생시키지 않음).

예제

#include <chrono>
#include <iostream>
#include <mutex>
#include <sstream>
#include <thread>
#include <vector>
using namespace std::chrono_literals;
std::mutex cout_mutex; // std::cout에 대한 접근 제어
std::timed_mutex mutex;
void job(int id)
{
    std::ostringstream stream;
    for (int i = 0; i < 3; ++i)
    {
        if (mutex.try_lock_for(100ms))
        {
            stream << "success ";
            std::this_thread::sleep_for(100ms);
            mutex.unlock();
        }
        else
            stream << "failed ";
        std::this_thread::sleep_for(100ms);
    }
    std::lock_guard<std::mutex> lock{cout_mutex};
    std::cout << '[' << id << "] " << stream.str() << '\n';
}
int main()
{
    std::vector<std::thread> threads;
    for (int i{0}; i < 4; ++i)
        threads.emplace_back(job, i);
    for (auto& th : threads)
        th.join();
}

가능한 출력:

[0] failed failed failed 
[3] failed failed success 
[2] failed success failed 
[1] success failed success

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 2093 C++11 try_lock_for 가 아무것도 throw하지 않음 timeout 관련 예외를 throw함

참고 항목

뮤텍스를 잠금, 뮤텍스를 사용할 수 없는 경우 차단
(public member function)
뮤텍스 잠금을 시도, 뮤텍스를 사용할 수 없는 경우 반환
(public member function)
뮤텍스 잠금을 시도, 지정된 시간 포인트에 도달할 때까지
뮤텍스를 사용할 수 없는 경우 반환
(public member function)
뮤텍스 잠금 해제
(public member function)