Call std :: lock () with std :: vector <mutex *>

I would like to replace the following code with std::lock():

for (mutex* m : mutexes) {
   m->lock();
}

In any case, can I call std::lock ()on these mutexes given a std::vector<mutex*>?

+3
source share
1 answer

Unfortunately, the standard library does not provide overload std::lock, which accepts a pair of iterators pointing to the objects being blocked. To use std::lock, you must know the number of objects to lock at compile time and pass them as arguments to the function. However, Boost provides an overload that accepts iterators and will work with std::mutex.

, , boost::indirect_iterator; (, std::vector<std::mutex*>, std::vector<std::mutex>). , std::mutex .)

#include <boost/thread/locks.hpp>
#include <boost/iterator/indirect_iterator.hpp>

#include <vector>
#include <mutex>

int main()
{
    using mutex_list = std::vector<std::mutex*>;
    mutex_list mutexes;

    boost::indirect_iterator<mutex_list::iterator> first(mutexes.begin()), 
                                                   last(mutexes.end());
    boost::lock(first, last);
}

+8

All Articles