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

后端 未结 1 491
别那么骄傲
别那么骄傲 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条回答
  •  梦毁少年i
    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 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

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