简体   繁体   中英

When to use defer_lock on std::shared_lock?

I see from 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?

When do we need to specify defer_lock parameter, for what kind of usage scenario?

Thanks!

You can always lock the mutex later, using lock() .

Sometimes, due to scoping rules, or whatever, you don't want to immediately lock anything when the lock object is created; but you still want to have the lock released, automatically, upon leaving the declaration's scope.

This allows you to instantiate a lock object, and not lock anything right away, but lock() it later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM