【问题标题】:Is there a latest example of using mutex under boost 1.48.0?是否有在 boost 1.48.0 下使用互斥锁的最新示例?
【发布时间】:2011-11-17 22:45:15
【问题描述】:

我在网上找到的大多数示例都已过时,使用的是 boost::mutex,但我没有声明 include 或 .有没有关于如何在 1.48.0 版中使用 boost::mutex 的明确示例? The tutorials in Chapter 27 (Threads) 非常不清楚,不提供任何代码示例。

【问题讨论】:

  • 我不记得从 boost 1.34 更新到更新版本时 boost::mutex 有任何问题。您能否详细介绍一下实际问题?
  • @BenC:实际上我现在发现这个问题很奇怪。使用 boost::mutex 可以成功编译,除了 Eclipse 中有一个错误提示说“boost::mutex 无法解析”,但是当我尝试实际构建项目时,它工作顺利。不知道为什么会这样。
  • 几年前我已经停止使用 Eclipse,所以我无法真正帮助您。有时 IDE 提供的信息可能会产生误导,但最重要的部分是编译不会出错。但是,如果您在编译过程中偶然发现与 boost::mutex 相关的错误,请随时与我们分享错误消息。

标签: c++ multithreading boost mutex


【解决方案1】:

查看此示例(boost::mutex 的用法在 Resource::use() 中介绍):

#include <boost/thread.hpp>
#include <boost/bind.hpp>

class Resource
{
public:
    Resource(): i(0) {}

    void use()
    {
        boost::mutex::scoped_lock lock(guard);
        ++i;
    }

private:
    int i;
    boost::mutex guard;
};

void thread_func(Resource& resource)
{
    resource.use();
}

int main()
{
    Resource resource;
    boost::thread_group thread_group;
    thread_group.create_thread(boost::bind(thread_func, boost::ref(resource)));
    thread_group.create_thread(boost::bind(thread_func, boost::ref(resource)));
    thread_group.join_all();
    return 0;
}

【讨论】:

    猜你喜欢
    • 2011-04-23
    • 2022-06-13
    • 1970-01-01
    • 2010-12-26
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多