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?