简体   繁体   English

何时在 std::shared_lock 上使用 defer_lock?

[英]When to use defer_lock on std::shared_lock?

I see from cppreference:我从 cppreference 看到:

std::shared_lock<Mutex>::shared_lock
 C++ Thread support library std::shared_lock 
shared_lock() noexcept;
(1) (since C++14)
shared_lock( shared_lock&& other ) noexcept;
(2) (since C++14)
explicit shared_lock( mutex_type& m );
(3) (since C++14)
shared_lock( mutex_type& m, std::defer_lock_t t ) noexcept;
(4) (since C++14)

And:和:

4) Does not lock the associated mutex.

Well, if this defer_lock means we don't lock the mutex, then what's the usage of this lock at all?好吧,如果这个 defer_lock 意味着我们不锁定互斥锁,那么这个lock到底有什么用呢?

When do we need to specify defer_lock parameter, for what kind of usage scenario?什么时候需要指定defer_lock参数,对于什么样的使用场景?

Thanks!谢谢!

You can always lock the mutex later, using lock() .您以后可以随时使用lock()锁定互斥锁。

Sometimes, due to scoping rules, or whatever, you don't want to immediately lock anything when the lock object is created;有时,由于范围规则或其他原因,您不想在创建锁 object 时立即锁定任何内容; but you still want to have the lock released, automatically, upon leaving the declaration's scope.但是您仍然希望在离开声明的 scope 时自动释放锁。

This allows you to instantiate a lock object, and not lock anything right away, but lock() it later.这允许您实例化一个锁 object,而不是立即锁定任何东西,而是稍后lock()它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 用 std::atomic 实现的 shared_lock - shared_lock implemented with std::atomic 何时使用C ++ 11互斥锁,锁,unique_lock,shared_lock等 - When to use C++11 mutex, lock, unique_lock, shared_lock, etc 将boost :: shared_lock升级为独占锁 - Upgrading boost::shared_lock to exclusive lock 错误:使用ReaderLock = std :: shared_lock的&#39;shared_mutex&#39;不是&#39;std&#39;的成员 <std::shared_mutex> ; - error: ‘shared_mutex’ is not a member of ‘std’ using ReaderLock = std::shared_lock<std::shared_mutex>; 同一线程中的 std::unique_lock 和 std::shared_lock - 不应该工作,但是可以吗? - std::unique_lock and std::shared_lock in same thread - shouldn't work, but does? 带有std :: shared_lock的std :: shared_mutex是读者还是作家更喜欢? - std::shared_mutex with std::shared_lock is reader or writer preferring? 我可以在 std::shared_mutex 上使用 std::shared_lock 更改数据吗? - Can I change data with a std::shared_lock on a std::shared_mutex? 将 shared_lock 升级为独特的锁使用、时序和设计 - Upgrade shared_lock to unique lock usage, timing and design 根据条件创建 shared_lock 或 unique_lock - Create shared_lock or unique_lock based on a condition Boost Shared_lock / Unique_lock,给作者优先权? - Boost Shared_lock / Unique_lock, giving the writer priority?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM