-2

I have a class that has its own worker thread, and some of the member variables of the class is shared between the main thread and the worker. How can I use a mutex to lock only the member variables that are being shared?

For instance, this does not work (since the block scope is outside any function).

class Foo {

public:
    // Some stuff
private:
    boost::thread *m_worker;
    Bar m_bar_nonshared;

    {
        boost::mutex m_mutex;
        Bar m_bar_shared;
    }
};
xcorat
  • 1,434
  • 2
  • 17
  • 34
  • 1
    Have a read in your book about what how to work with mutexes, or take a look at a tutorial, maybe [this](http://www.thegeekstuff.com/2012/05/c-mutex-examples/?refcom) one so that you can understand what a mutex actually is – UKMonkey Jan 10 '17 at 17:17

1 Answers1

0

A mutex doesn't lock member variables, it locks code. The only way for it to lock a member variable is if it locks the only code that accesses it.

That is, put the lock in the access functions (get/set) and don't allow access to the members any other way.

A. Levy
  • 29,056
  • 6
  • 39
  • 56
  • Using a mutex in each getter and setter will ensure that all threads see the latest updates to the variables, but it won't actually provide any mutual exclusion. Imagine an object with members A, B, and C, where A+B+C must always equal zero. Locking the getters and setters for A, B, and C won't protect that invariant because nothing's locked in between the individual gets and sets. You have to keep the lock locked during the whole time you are adjusting the values, and you have to keep it locked during the whole time that you care about the sum being zero. – Solomon Slow Jan 10 '17 at 17:23
  • @jameslarge: What you say is true. I only saw one variable being referenced as being shared in the given example though. I didn't mean for my answer to be the canonical way to use mutices, only to correct the principle misunderstanding here. That is, a mutex doesn't lock data it locks code that accesses the data. Maintaining data integrity and invariants is a responsibility of that code, yes, but that wasn't the point of my answer. – A. Levy Jan 10 '17 at 17:36
  • Having setters getters lock the mutex isn't really the answer since I wanted the member functions to access the locked mutex anyway. But yah, thx – xcorat Jan 10 '17 at 17:55