Difference between boost::mutex and boost::timed_mutex

boost, c++

Solution

I have not looked at the source, but I used these a few days ago, and the timed mutexes function differently. They block until the time is up, then return. A unique lock will block until it can get the lock.

A try lock will not block, and you can then test to see if it has ownership of the lock. A timed lock will block for the specified amount of time, then behave as a try lock - that is, cease blocking, and you can test for ownership of the lock.

I believe that internally some of the different boost locks are typedefs for unique lock since they all use unique locking. The typedef names are there so that you can keep track of what you are using different ones for, even though you could use different functionality and confuse your client code.

Edit: here is an example of a timed 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 provide a specific answer to your question, yes, it would be wrong to use `boost::mutex` as a `TimedLockable` because `boost::timed_mutex` is provided for this purpose. If they are the same thing in the source and this is undocumented, this is unreliable behavior and you should follow the documentation. (My code example did not used `timed_mutex` at first but I updated it)

Problem

According to Boost documentation `boost::mutex` and `boost::timed_mutex` are supposed to be different. The first one implements `Lockable Concept`, and the second - `TimedLockable Concept`. But if you take a look at the source, you can see they're basically the same thing. The only difference are lock typedefs. You can call `timed_lock` on `boost::mutex` or use `boost::unique_lock` with timeout just fine. ``` 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's the rationale behind that? Is it some remnant of the past, is it wrong to use `boost::mutex` as a `TimedLockable`? It's undocumented after all.

Original source