使用 boost 线程监视模式
作为 boost::thread 的新手,前几天我尝试编写一个 BlockingQueue (在我看来,这是有史以来最实用的同步构造)。这是使用信号量或条件变量来完成的,之前在 Windows 和 Linux 上都做过,但从未使用过 boost。
因此,在有可用“监视器”的语言中(您知道,带有锁定、等待和通知的监视器),您只需使用它:
T BlockingQueue::take()
{
scopelock(monitor);
while (queue.empty())
monitor.wait();
T ret = queue.front();
queue.pop();
return ret;
}
据我所知,“监视器”是使用 boost::condition_variable_any 串联来完成的带有 boost::mutex 。但是,condition_variable_any 已经包含互斥锁! (称为internal_mutex)。所以这就是为什么我一开始认为 condition_variable_any 是整个监视器,但事实证明互斥体无法从外部访问,并且在等待之前无法锁定它等。
任何人都知道 boost::condition_variable_any::internal_mutex 的目的是什么?就我而言,这让我真的很困惑,因为我知道等待 pthread_cond_t 必须在互斥锁锁定的情况下完成 - 但哪个互斥锁?谢谢。
Being new to boost::thread I was trying the other day to write a BlockingQueue (in my opinion the most practical synchronization construct ever). That's accomplished either using a semaphore or a condition variable, did both previously on windows respectively linux but never using boost.
So, in languages where you have a "Monitor" available (you know, the one with lock, wait, and notify) you just use that:
T BlockingQueue::take()
{
scopelock(monitor);
while (queue.empty())
monitor.wait();
T ret = queue.front();
queue.pop();
return ret;
}
From what I could tell the "Monitor" is accomplished using a boost::condition_variable_any in tandem with a boost::mutex. BUT, the condition_variable_any already contains a mutex! (called internal_mutex). So that's why I thought at first that condition_variable_any is the whole Monitor, but as it turns out the mutex is not accesible from outside and you can't lock it before waiting etc.
Anyone know what's the purpose of boost::condition_variable_any::internal_mutex? In my case, It got me really confused bc I know that waiting on a pthread_cond_t must be done with the mutex locked - but which mutex?? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论