글
std::mutex의 try_lock을 사용하면 뮤텍스의 소유권을 가질 수 있으면 true를 반환하고, 그렇지 못하면 바로 false를 반환하므로 소유권을 얻고 싶으면 또 다시 try_lock을 호출해야 합니다. 그런데 공유자원을 사용하는 시간이 아주 짧은 경우도 있다면 특정 시간까지만 계속 락을 시도하여 뮤텍스의 소유권을 가지기를 바라는 경우가 있습니다. 이럴 때 사용하는 것이 timed_mutex입니다.
timed_mutex는 std::mutex의 모든 기능을 다 가지고 있으면서 try_lock_for와 try_lock_until 함수 두 개가 더 있습니다. 이 함수들은 시간을 사용하여 뮤텍스 소유를 시도합니다. 시간은 std::chrono로 설정합니다.
try_lock_for는 지정한 시간 동안 락을 걸어봅니다.
template<class Rep, class Period>
bool try_lock_for(const chrono::duration<Rep, Period>& Rel_time);
// 10초 동안 mutex의 소유권을 얻을 때까지 시도
if( mutex.try_lock_for(std::chrono::seconds(10)) )
{
// 공유 자원 사용
mutex.unlock();
}
try_lock_until은 지정한 시간까지 뮤텍스의 소유를 시도합니다.
template<class Clock, class Duration>
bool try_lock_for(const chrono::time_point<Clock, Duration>& Abs_time);
bool try_lock_until(const xtime *Abs_time);
std::chrono::system_clock::time_point CurTime = std::chrono::system_clock::now();
std::chrono::seconds dura_sec( 5 );
// 현재 시간에서 5초 후까지만 mutex를 소유하려고 시도한다
if( mutex.try_lock_until(CurTime + dura_sec) )
{
// 공유 자원 사용
mutex.unlock();
}
recursive_timed_mutex
recursive_timed_mutex는 std::mutex에 시간 기능이 추가된 timed_mutex 처럼 recursive_mutex에 시간 기능이 추가된 것입니다.
recursive_mutex에 추가된 함수나 사용 방법은 timed_mutex와 비슷합니다.
댓글