【发布时间】:2020-06-05 19:56:19
【问题描述】:
我对@987654322@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 是否保护我的返回值?
【问题讨论】:
-
我确定我已经找到了这个问题的副本。但答案是肯定的,
std::lock_guard返回后会被销毁。 -
可能是 Is a copy-on-return operation executed prior or after lock_guard destructor? 的副本,除了
get1()和get2()被get_a()和get_b()替换:p
标签: c++ multithreading thread-safety mutex