I have a question about lock_guard
s and return values. I would like to illustrate my question with some code:
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_;
};
The above class is a simple implementation of a Semaphore
. Which of the get-methods is thread-safe? Is get2
good enough or do I have to use get1
? Do I have to copy the internal value n_
to a temporary variable or can I just return it right away?
This post boils-down to the question: Does the lock_guard protect my return value?