用std :: vector< mutex *>调用std :: lock() [英] Calling std::lock () with std::vector <mutex*>

查看:129
本文介绍了用std :: vector< mutex *>调用std :: lock()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用std::lock()替换以下代码:

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

反正我可以在给定std::vector<mutex*>的那些互斥锁上调用std::lock ()吗?

Is there anyway I could invoke std::lock () on those mutexes given a std::vector<mutex*>?

推荐答案

不幸的是,标准库没有提供重载,它需要迭代器,并且它可以与std::mutex一起使用.

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.

您需要的另一块脚手架是 boost::indirect_iterator ;当您取消引用迭代器时,这将应用额外的取消引用(这是必需的,因为您有std::vector<std::mutex*>而不是std::vector<std::mutex>.无论如何,由于无法复制或移动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);
}

实时演示

这篇关于用std :: vector&lt; mutex *&gt;调用std :: lock()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆