Thread-safe get (accessor method)

c, c++, multithreading

Solution

Since you gave C++ as an option, you can wrap the mutex lock/unlock. You can then return the value directly:

class lock_wrapper
{
public:
    lock_wrapper()
    {
        acquireLock();
    }
    ~lock_wrapper()
    {
        releaseLock();
    }
};

int getVariableValue()
{
    lock_wrapper lw;
    return gnVariable;
}

This will also come in handy if you ever need to do a lock/unlock around code that can throw an exception.

Problem

I'm currently using the following code for thread-safe access of a variable. ``` int gnVariable; void getVariableValue(int *pnValue) { acquireLock(); //Acquires the protection mechanism *pnValue = gnVariable; releaseLock(); //Releasing the protection mechanism } ``` I would like to change my API signature to a more user-friendly ``` int getVariableValue(void); ``` How should I rewrite the function - such that the users of the API don't have to bother about the locking/unlocking details?

Original source