gpt4 book ai didi

c++ - 如何避免使用 lock_guard 锁定?

转载 作者:行者123 更新时间:2023-11-28 01:25:32 27 4
gpt4 key购买 nike

https://en.cppreference.com/w/cpp/thread/lock_guard

(constructor)
constructs a lock_guard, optionally locking the given mutex

如果它是可选的,避免锁定的方法是什么?

最佳答案

这是避免 lock_guard 构造函数锁定给定的 mutex 的一种方法:

std::mutex mtx;
mtx.lock();
std::lock_guard<std::mutex> lck(mtx, std::adopt_lock);

目的是让您的 lock_guard 获得您已经锁定的 mutex 的所有权。

发件人:https://en.cppreference.com/w/cpp/thread/lock_guard/lock_guard

explicit lock_guard( mutex_type& m ); (1) (since C++11)
lock_guard( mutex_type& m, std::adopt_lock_t t ); (2) (since C++11)
lock_guard( const lock_guard& ) = delete; (3) (since C++11)
Acquires ownership of the given mutex m.

1) Effectively calls m.lock(). The behavior is undefined if m is not a recursive mutex and the current thread already owns m.  
2) Acquires ownership of the mutex m without attempting to lock it.

The behavior is undefined if the current thread does not own m.
3) Copy constructor is deleted.
The behavior is undefined if m is destroyed before the lock_guard object is.

关于c++ - 如何避免使用 lock_guard 锁定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54033896/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com