c++ - Thread-safe get (accessor method) -


I am currently using the following code for thread-safe access to a variable.

  integer; VaryableValue (int * pnValue) {acquireLock (); // secures security mechanism * pnValue = gnVariable; ReleaseLock (); // Issue security system}  

I would like to change my API signature to more user-friendly

  int getVariableValue (zero);  

I should rewrite the function - such as the users of the API do not have to worry about locking / unlocking details?

Since you have given C ++ as an option, you wrap Mute Axel Lock / Unlock can do. Then you can return the value directly:

  class lock_wrapper {public: lock_wrapper () {acquireLock (); } ~ Lock_wrapper () {releaseLock (); }}; Int getVariableValue () {lock_wrapper lw; Return GNVAAB; }  

This will also be useful if you ever need to lock / unlock which can throw an exception.


Comments