Difference between boost :: mutex and boost :: timed_mutex

According to the documentation of Boost boost::mutex and boost::timed_mutex it is assumed that they are different from each other. The first implements the Lockable Concept , and the second TimedLockable Concept .

But if you look at the source, you will see that they are basically the same. The only difference is blocking typedefs. You can call timed_lock on boost::mutex or use boost::unique_lock with minimal latency.

 typedef ::boost::detail::basic_timed_mutex underlying_mutex; class mutex: public ::boost::detail::underlying_mutex class timed_mutex: public ::boost::detail::basic_timed_mutex 

What is the reason for this? This is some remnant of the past, is it wrong to use boost::mutex as TimedLockable ? In the end, this is undocumented.

+4
source share
1 answer

I did not look at the source, but I used them a few days ago, and temporary mutexes function differently. They are blocked until the time runs out, and then return. The unique lock is locked until it can get the lock.

The try lock will not be blocked, and you can then check to see if it has ownership of the lock. A temporary lock will be blocked for a certain time, and then behave like a try lock, that is, stop the lock, and you can check the ownership of the lock.

I believe that internally some of the various towing locks are typedefs for unique locking, as they all use unique locking. There are typedef names here so you can keep track of why you are using different ones, although you can use different functions and confuse the client code.

Edit: here is an example of time lock:

 boost::timed_mutex timedMutexObj; boost::mutex::scoped_lock scopedLockObj(timedMutexObj, boost::get_system_time() + boost::posix_time::seconds(60)); if(scopedLockObj.owns_lock()) { // proceed } 

For reference: http://www.boost.org/doc/libs/1_49_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_concepts.timed_lockable.timed_lock

Edit again: to give a specific answer to your question, yes, it would be wrong to use boost::mutex as TimedLockable , because boost::timed_mutex provided for this purpose. If they are the same in the source and this is undocumented, this is an unreliable behavior and you should follow the documentation. (My sample code did not use timed_mutex at first, but I updated it)

+3
source

Source: https://habr.com/ru/post/1414392/


All Articles