c++ - 将 boost::bind 与包含 boost::mutex 的类一起使用

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

我正在使用 watchdir 将项目添加到内部集合的服务器上工作。 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 需要可复制的参数。

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

我该怎么做才能解决这个问题?

最佳答案

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

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

写:

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

关于c++ - 将 boost::bind 与包含 boost::mutex 的类一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13987655/

相关文章:

c++ - 引用函数返回值

c++ - 现在和现在之间的差异时间会产生 1 小时的差异 (C++)

c++ - 与 Boost.Bind 相比,Boost.Functional 有什么好处?

c++ - 在 boost::bind 中使用 boost 信号

C++ - std::map 不需要转换的替代方案

c++ - 如何设置二维窗口

c++ - 在派生类中管理线程生命周期

c++ - 如何使用boost使类成员函数成为线程函数

c++ - TinyXMl多线程写入数据

c++ - Boost::bind 与对象占位符