Usage of boost::unique_lock::timed_lock

后端 未结 2 1115
感情败类
感情败类 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.

    0 讨论(0)
  • 2021-01-21 18:14

    You are right. The example doesn't properly handle the state of when the mutex fails to lock. If you read closely just below that example you'll see this quoted there:

    The above example uses various methods to illustrate some of the features provided by boost::unique_lock. Certainly, the usage of these features does not necessarily make sense for the given scenario; the usage of boost::lock_guard in the previous example was already adequate. This example is rather meant to demonstrate the possibilities offered by boost::unique_lock.

    0 讨论(0)
提交回复
热议问题