From a Container class, I'd like to lock
a vector of boost::mutex
, each one owned by a Controlled instance (weird code design, but for MWE purpose only).
// std::vector<Controlled*> _vData;
void Container::main_method()
{
for (int i=0; i<_vData.size(); i++)
{
boost::mutex::scoped_lock my_lock(_vData.at(i)->_mutex);
this->processing(i);
}
// precondition for post_processing(): all processing() calls done
for (int i=0; i<_vData.size(); i++)
{
boost::mutex::scoped_lock my_lock(_vData.at(i)->_mutex);
this->post_processing(i);
}
}
But since processing
is cpu-bound and Controlled objects are modified from elsewhere in the mean time, I'd like to simply do a cycled scoped_lock
at the beginning of the main_method
, in order to lock everything and asap, such as
void Container::desired_main_method()
{
for (int i=0; i<_vData.size(); i++)
{
boost::mutex::scoped_lock my_lock(_vData.at(i)->_mutex);
}
// locks destroyed here, aren't they ?
for (int i=0; i<_vData.size(); i++)
{
this->processing(i);
}
for (int i=0; i<_vData.size(); i++)
{
this->post_processing(i);
}
}
Problem is, if I understanded well the RAII idiom and the scoped_lock
context, that in this way, the locks would go out of scope soon after the lock for
cycle ends.
I've tried to new
an array of locks at Container ctor and to delete
it at its dtor, but I guess this is against the RAII idiom itself.
What did I misunderstand, or how could I refactor the whole issue?
Assuming that your question is: "how do I use a RAII-like scoped lock for multiple mutexes at the same time?"
Then you can either create your own RAII-wrapper for multiple locks or use something like a scope guard.
(Untested pseudocode, but hope you get the idea.)
template <typename TIterator>
class multiple_lock_guard
{
private:
TIterator _begin, _end;
multiple_lock_guard(TIterator begin, TIterator end)
: _begin{begin}, _end{end}
{
for(auto it = _begin; it != _end; ++it)
{
it->_mutex.lock();
}
}
~multiple_lock_guard()
{
for(auto it = _begin; it != _end; ++it)
{
it->_mutex.unlock();
}
}
};
You can use it as follows:
void Container::desired_main_method()
{
multiple_lock_guard mlg(std::begin(_vData), std::end(_vData));
for(int i = 0; i < _vData.size(); i++)
{
this->processing(i);
}
for(int i = 0; i < _vData.size(); i++)
{
this->post_processing(i);
}
}