使用Boost ::与包含Boost :: Mutex的类绑定

Using boost::bind with a class containing a boost::mutex

本文关键字:Boost 绑定 包含 使用 Mutex      更新时间:2023-10-16

我正在使用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)

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

我不喜欢静态静音的想法,因为它在语义上是错误的,因为这里的静音的角色是防止在修改时阅读我的收藏。

我该怎么办来解决这个问题?

使用std :: ref或std :: cref围绕互不rutex。也就是说,而不是:

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

写:

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