Usage of boost::unique_lock::timed_lock

后端 未结 2 1143
感情败类
感情败类 2021-01-21 17:44

boost::timed_lock

void wait(int seconds) 
{ 
  boost::this_thread::sleep(boost::posix_time::seconds(seconds)); 
} 

boost::timed_mutex mutex; 

void thread() 
{          


        
2条回答
  •  天命终不由人
    2021-01-21 18:10

    You are right and the example does NOT guarantee the lock is always properly acquired before executing the protected code.

    Given the explanation below the example:

    The above program passes boost::try_to_lock as the second parameter to the constructor of boost::unique_lock. Whether or not the mutex has been acquired can be checked via the owns_lock() method afterwards. In case it has not - owns_lock() returns false - another function provided by boost::unique_lock is used: timed_lock() waits for a certain time to acquire the mutex. The given program waits for up to one second which should be more than enough time to acquire the mutex.

    The example actually shows the three fundamental ways of acquiring a mutex: lock() waits until the mutex has been acquired. try_lock() does not wait but acquires the mutex if it is available at the time of the call and returns false otherwise. Finally, timed_lock() tries to acquire the mutex within a given period of time. As with try_lock(), success or failure is indicated by the return value of type bool.

    the authors seem aware of the problem (given that the document the return value of timed_lock) but did not think a re-test if the lock had been acquired was needed (as demonstrated by them saying "waits for up to one second which should be more than enough time to acquire the mutex").


    One error in your understanding:

    If after the specified time lapsed and the object still cannot get the lock, then the boost::timed_lock will return false.

    This is not true. timed_lock will 'continuously' try to obtain the lock, but give up if the specified time has expired.

提交回复
热议问题