这个问题在这里已经有了答案:
Is a copy-on-return operation executed prior or after lock_guard destructor? [duplicate]
(1 个回答)
Timing of scope-based lock guards and return values
(2 个回答)
去年关闭。
我有一个关于 lock_guard
的问题s 和返回值。我想用一些代码来说明我的问题:
class Semaphore
{
public:
Semaphore() = delete;
Semaphore(int n);
/**
* Increases semaphore by one.
*/
void up()
{
std::lock_guard<std::mutex> lg(m_);
++n_;
}
/**
* Decreases semaphore by one.
*/
void down()
{
std::lock_guard<std::mutex> lg(m_);
--n_;
}
/**
* Returns the underlying value of the semaphore.
*/
int get1() const
{
std::lock_guard<std::mutex> lg(m_);
int tmp = n_;
return tmp;
}
/**
* Returns the underlying value of the semaphore.
*/
int get2() const
{
std::lock_guard<std::mutex> lg(m_);
return n_;
}
private:
mutable std::mutex m_;
int n_;
};
上面的类是一个
Semaphore
的简单实现.哪个 get 方法是线程安全的?是 get2
足够好还是我必须使用 get1
?我是否必须复制内部值 n_
到临时变量还是我可以立即返回它?这篇文章归结为问题: lock_guard 是否保护我的返回值?
最佳答案
get2()
足以保护返回值。n_
是按值返回的,因此将变量的拷贝与您的 return n_
一起返回给调用者。陈述。您的 lock_guard
将确保 n_
在该拷贝返回给调用者之前不会被更改,然后它会被销毁从而释放锁。
返回拷贝并没有错,但不会给您任何额外的好处。此外,在任何情况下,您都需要保持锁定,直到拷贝也被返回。因此与 get1
除非编译器对其进行优化,否则您会为额外的拷贝分配付出代价而不会获得太多 yield 。
关于c++ - lock_guard 是否保护返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60337759/