void wait(int seconds)
{
boost::this_thread::sleep(boost::posix_time::seconds(seconds));
}
boost::timed_mutex mutex;
void thread()
{
for (int i = 0; i < 5; ++i)
{
wait(1);
boost::unique_lock<boost::timed_mutex> lock(mutex, boost::try_to_lock);
if (!lock.owns_lock())
lock.timed_lock(boost::get_system_time() + boost::posix_time::seconds(1));//<<<<
std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl;
boost::timed_mutex *m = lock.release();
m->unlock();
}
}
Question> I have problems to understand the following lines:
if (!lock.owns_lock())
lock.timed_lock(boost::get_system_time() +
boost::posix_time::seconds(1));//<<<<
Here is my understanding. Assume lock.owns_lock() returns false which means the current object DOES NOT own the lock on the lockable object. So next line will be executed. If after the specified time lapsed and the object still cannot get the lock, then the boost::timed_lock will return false. So the following line will be executed???
std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl;
Is this idea correct? I think the purpose of the code is to make sure the above line is executed iff the object has the lock. But based on my understanding(i guess is NOT correct), the above line always gets run!
Where is the problem?
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 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:
This is not true.
timed_lockwill ‘continuously’ try to obtain the lock, but give up if the specified time has expired.