I'm working on a server using a watchdir to add items to an internal collection. The watchdir is browsed periodically by a thread which is created like this :
this->watchDirThread = new boost::thread(boost::bind(&Filesystem::watchDirThreadLoop,
this,
this->watchDir,
fileFoundCallback));
The fileFoundCallback
parameter is also created via boost::bind
:
boost::bind(&Collection::addFile, this->collection, _1)
I would like to protect my collection from concurrent access using a mutex but my problem is that the boost::mutex
class is non copyable, therefore there can't be a mutex in my Collection
class since boost::bind
requires copyable parameters.
I don't like the idea of a static mutex because it would be semantically wrong as the role of the mutex here is to prevent my collection to be read while it's being modified.
What can I do to solve this problem ?
Use std::ref or std::cref around the mutex. That is, instead of:
boost::mutex yourmutex;
boost::bind(..., yourmutex, ...);
write:
boost::mutex yourmutex;
boost::bind(..., std::ref(yourmutex), ...);