【问题标题】:Using boost::bind with a class containing a boost::mutex将 boost::bind 与包含 boost::mutex 的类一起使用
【发布时间】:2012-12-08 21:17:28
【问题描述】:

我正在使用监视目录将项目添加到内部集合的服务器上工作。 watchdir 由这样创建的线程定期浏览:

this->watchDirThread = new boost::thread(boost::bind(&Filesystem::watchDirThreadLoop,
                                                      this,
                                                      this->watchDir,
                                                      fileFoundCallback));

fileFoundCallback 参数也是通过boost::bind 创建的:

boost::bind(&Collection::addFile, this->collection, _1)

我想使用互斥锁来保护我的集合免受并发访问,但我的问题是 boost::mutex 类是不可复制的,因此我的 Collection 类中不能有互斥锁,因为 boost::bind 需要可复制参数。

我不喜欢静态互斥锁的想法,因为它在语义上是错误的,因为这里互斥锁的作用是防止我的集合在修改时被读取。

我能做些什么来解决这个问题?

【问题讨论】:

    标签: c++ boost-thread boost-bind boost-mutex


    【解决方案1】:

    在互斥体周围使用std::ref or std::cref。也就是说,而不是:

    boost::mutex yourmutex;
    boost::bind(..., yourmutex, ...);
    

    写:

    boost::mutex yourmutex;
    boost::bind(..., std::ref(yourmutex), ...);
    

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 2011-12-13
      • 2011-12-15
      • 2011-01-17
      • 1970-01-01
      相关资源
      最近更新 更多