使用 boost 线程监视模式

发布于 2025-01-02 21:59:10 字数 710 浏览 5 评论 0原文

作为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文