Vectors of lock_guards
Vectors of lock_guards
我正在处理一些多线程代码(处理并发数据结构),其中一部分需要锁定一组互斥对象。对于我的实现,我使用了一个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
要求类型为MoveInsertable
和EmplaceConstructible
,而std::lock_guard
不适用。
相关文章:
- 尝试构建"lock-free"数据结构C++
- 为什么 c++11 std::lock 和 std::scoped_lock 至少需要 2 个参数?
- 为什么"weak.lock()"返回"nullptr" "auto weak=std::make_shared<int>(42);"的定义?
- DRD 报告"conflicting load" std::mutex::lock 上的错误
- 在 std::tie 中使用 std::weak_ptr::lock()
- std::lock_guard 怎么可能比 std::mutex::lock() 更快?
- std::mutex::lock() 产生奇怪(和不必要的)ASM 代码
- "lock cmpxchg"如何在装配中工作?
- std::lock 仍然导致死锁
- 在任何地方对C++中所有并行线程中的所有锁定和解锁实例使用相同的 std::mutex 和 lock 对象
- 我们是否需要对多线程 x32 系统使用 lock 来读取或写入 uint32_t 变量
- 使用Mutex,lock_guard,在课堂中正确地lock
- 当我调用lock()时,为什么std :: mutex会引发异常
- mutex.lock vs unique_lock
- 使用 std::lock (c++11) 的大量 CPU 负载
- 我是否必须使用neak_ptr.lock()只是为了测试它是否指向有效的对象
- std::lock() equivalent for boost::shared_mutex?
- mutex::lock() 检查一次解锁状态是否已经被另一个线程锁定?
- 为什么在 std::lock 中没有超时支持
- 使用#include和Inclusion Guards的独立文件中的C++继承