gpt4 book ai didi

c++ - boost::unique_lock::timed_lock 的用法

转载 作者:搜寻专家 更新时间:2023-10-31 01:11:57 25 4
gpt4 key购买 nike

boost::timed_lock

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();
}
}

timed_lock

问题> 我无法理解以下几行:

  if (!lock.owns_lock()) 
lock.timed_lock(boost::get_system_time() +
boost::posix_time::seconds(1));//<<<<

这是我的理解。假设 lock.owns_lock() 返回 false,这意味着当前对象不拥有可锁定对象上的锁。所以下一行将被执行。如果在指定的时间过去后对象仍然无法获得锁,则 boost::timed_lock 将返回 false。所以下面一行会被执行???

std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl; 

这个想法对吗?我认为代码的目的是确保在对象具有锁的情况下执行上面的行。但根据我的理解(我猜是不正确的),上面的行总是运行!

问题出在哪里?

最佳答案

你是对的,这个例子并不能保证在执行 protected 代码之前总是正确地获取锁。

给出示例下面的解释:

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.

作者似乎意识到了这个问题(假设记录了 timed_lock 的返回值)但认为是否需要重新测试是否需要锁定(正如他们所说的那样) “最多等待一秒钟,这应该有足够的时间来获取互斥量”)。


你理解上的一个错误:

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

这不是真的。 timed_lock 将“持续”尝试获取锁,但如果指定时间已过则放弃。

关于c++ - boost::unique_lock::timed_lock 的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14200305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com