I have a simple class with one private member that is accessible via get() and set() in a multithreaded environment (multi readers/multi writers). how do I lock a Get() as it only has a return statement?
class MyValue
{
private:
System::CriticalSection lock;
int val { 0 };
public:
int SetValue(int arg)
{
lock.Enter();
val = arg;
lock.Leave();
}
int GetValue()
{
lock.Enter();
return val;
//Where should I do lock.Leave()?
}
}
Don't lock anything. In your example, it is enough if you make your member an std::atomic
integer.
You do not need anything else here. As a matter of fact, due to Intel architecture (strong memory ordering model), this std::atomic
is not even likely to cause any performance issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With