什么是锁定多个std :: mutex'es的最好的方法? [英] What's the best way to lock multiple std::mutex'es?
问题描述
当我们要锁定多个 std :: mutex
'时,我们使用 std :: lock()
。但 std :: lock()
不提供RAII功能。
When we want to lock multiple std::mutex
'es, we use std::lock()
. But std::lock()
does not provide RAII feature.
当我们要锁定 std :: mutex
在RAII方式,我们使用 std :: lock_guard
。但 std :: lock_guard
不能安全地锁定多个 std :: mutex
。
When we want to lock a std::mutex
in RAII way, we use std::lock_guard
. But std::lock_guard
cannot lock multiple std::mutex
'es safely.
有什么方法可以利用这两种方法的优点,以RAII方式锁定多个 std :: mutex
'?
Is there any way to take the advantages of both methods, to lock multiple std::mutex
'es in RAII way?
推荐答案
是的,您可以使用 std :: unique_lock
与 std :: defer_lock
。它告诉unique_lock不立即锁定互斥体,而是要构建RAII包装器。
Yes, you can use a std::unique_lock
with std::defer_lock
. It tells the unique_lock to not lock the mutex immediately, but to build the RAII wrapper.
std::unique_lock<std::mutex> lk1(mutex1, std::defer_lock);
std::unique_lock<std::mutex> lk2(mutex2, std::defer_lock);
std::lock(lk1, lk2);
由于其变化性质 std :: lock
不仅绑定到两个参数,但可以使用与您的编译器支持的参数一样多。
Due to its variadic nature std::lock
is not bound to only two arguments but can be used with as many arguments as your compiler has support for.
Howard Hinnant也指出了一个关于效能的有趣事实,您可以检查这个链接,如果你有兴趣。他解决了性能问题,并显示 std :: lock
可以有效地实现,我也可以推荐阅读该帖子中的所有注释。
Howard Hinnant also pointed out an interesting fact about performance, you can check this link if you are interested. He addresses performance concerns and shows that std::lock
can be implemented efficiently, I can also recommend to read all the comments in that post.
这篇关于什么是锁定多个std :: mutex'es的最好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!