-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; } }; 
1
  • 1
    Have a read in your book about what how to work with mutexes, or take a look at a tutorial, maybe this one so that you can understand what a mutex actually is Commented Jan 10, 2017 at 17:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
@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.
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.