Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ criticalsection for getter

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()?
    }   
}
like image 799
bsobaid Avatar asked Feb 08 '23 12:02

bsobaid


1 Answers

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.

like image 177
SergeyA Avatar answered Feb 20 '23 06:02

SergeyA