Vectors of lock_guards

Vectors of lock_guards

本文关键字:guards lock of Vectors      更新时间:2023-10-16

我正在处理一些多线程代码(处理并发数据结构),其中一部分需要锁定一组互斥对象。对于我的实现,我使用了一个lock_guard向量,因为我不一定知道需要锁定多少互斥,而且我可能会遇到异常情况,这将迫使我解锁所有互斥并重新启动。因此产生矢量的原因。

我尝试使用的代码可以归结为:

#include <mutex>
#include <vector>

using namespace std;
int main( int argc, char** argv ) {
    vector<recursive_mutex> vec(10);
    vector<lock_guard<recursive_mutex>> lgv;
    for( auto it = vec.begin(); it != vec.end(); ++it ) {
        lgv.emplace_back( *it );
    }
    return 0;
}

当我试图编译这个(G++5.3.1使用--std=c++11)时,我得到了以下错误(有些提炼):

In file included from foo.cpp:1:0:
/usr/include/c++/5.3.1/mutex:385:7: note: declared here
   lock_guard(const lock_guard&) = delete;

根据我对template_back的理解,库不应该试图使用lock_guard的复制构造函数——它应该在原地执行构造。我是正确地理解了应该发生的事情,还是我的理解有缺陷?

仅供参考,我已经尝试使用unique_lock,这将很好地编译。然而,我对这种(明显的)差异感到好奇。

我认为,这个问题反映了一种使用unique_lock的尝试,OP说它有效。lock_guard的相同示例不起作用,因为std::vector::emplace_back要求类型为MoveInsertableEmplaceConstructible,而std::lock_guard不适用。