Alex Rivera | Logout

Does a getter function need a mutex?

Asked 2010-02-12T14:31:28.477
17

I have a class that is accessed from multiple threads. Both of its getter and setter functions are guarded with locks.

Are the locks for the getter functions really needed? If so, why?

class foo {
public:
    void setCount (int count) {
        boost::lock_guard<boost::mutex> lg(mutex_);
        count_ = count;
    }

    int count () {
        boost::lock_guard<boost::mutex> lg(mutex_); // mutex needed?
        return count_;
    }

private:
    boost::mutex mutex_;
    int count_;
};
Edit
Report

2 Answers

2

in you case probably not, if your cpu is 32 bit, however if count is a complex object or cpu needs more than one instruction to update its value, then yes

answered 2010-02-12T14:37:16.907
1

It depends on the exact implementation of the object being locked. However, in general you do not want someone modifying (setting?) an object while someone else is in the process of reading (getting?) it. The easiest way to prevent that is to have a reader lock it.

In more complicated setups the lock will be implemented in such a way that any number of folks can read at once, but nobody can write to it while anyone is reading, and nobody can read while a write is going on.

answered 2010-02-12T15:13:56.483

Your Answer