Calling std::lock () with std::vector

后端 未结 1 489
别那么骄傲
别那么骄傲 2021-02-10 14:00

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

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

Is there anyway I could

相关标签:
1条回答
  • 2021-02-10 14:32

    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<std::mutex*> and not std::vector<std::mutex>. The latter would not be very useful anyway since std::mutex cannot be copied or moved.)

    #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);
    }
    

    Live demo

    0 讨论(0)
提交回复
热议问题