I would like to replace the following code with std::lock()
:
for (mutex* m : mutexes) {
m->lock();
}
Is there anyway I could
Unfortunately the standard library doesn't provide an overload for std::lock that takes a pair of iterators pointing to lockable objects. To use std::lock
you must know the number of lockable objects at compile time, and pass them as arguments to the function. However, Boost does provide an overload that takes iterators, and it'll work with std::mutex
.
The other piece of scaffolding you'll need is boost::indirect_iterator; this will apply an extra dereference when you dereference the iterator (needed because you have std::vector
and not std::vector
. The latter would not be very useful anyway since std::mutex
cannot be copied or moved.)
#include
#include
#include
#include
int main()
{
using mutex_list = std::vector;
mutex_list mutexes;
boost::indirect_iterator first(mutexes.begin()),
last(mutexes.end());
boost::lock(first, last);
}
Live demo