Recommended Posts

It is a pretty noob question, but if I have a mutex around a block of code, does that just prevent multiple threads entering this block of code at the same time? Or does it also lock variables used in the block?
For example:

In order for this class to be properly thread safe, I need to stop a thread reading x while it is being updated. Does my example do this, or does it simply make the setter thread-safe?
My real example is a container, where one thread can insert into the container and another can remove from it. For example is this thread safe?

Share this post

Link to post

Share on other sites

I don't know boost::mutex's,I don't see how the local variable will be connected to the other local variable, so I guess you are protecting each function alone, if the mutex class automatically locks and unlocks.

I am guessing proper use will be something along:

class A{private: boost::mutex mut;

public:void Set(value) { mut.lock();// set stuff mut.unlock(); }

value Get() { mut.lock();// get stuff mut.unlock(); }};

0

Share this post

Link to post

Share on other sites

Boost mutexes don't allow you to explicitly lock and unlock. Essentially the constructor calls lock() internally and the destructor calls unlock() internally - it's very nice as it means the lock automatically dies at the end of the function.

Reading the docs again it seems to suggest that *this is what gets locked. But does that mean the mutex, or the class containing the method using the mutex?

Share this post

Link to post

Share on other sites

Original post by d000hgBoost mutexes don't allow you to explicitly lock and unlock. Essentially the constructor calls lock() internally and the destructor calls unlock() internally - it's very nice as it means the lock automatically dies at the end of the function.

Reading the docs again it seems to suggest that *this is what gets locked. But does that mean the mutex, or the class containing the method using the mutex?

Can anyone comment further?

I haven't used any of boost's threading facilities, but I think you've missed a bit.

What you want is the mutex to be a class member, as Iftah suggested. However, according to the documentation, boost::mutex provides an inner class, boost::mutex::scoped_lock, which takes a mutex reference to its constructor. It is the scoped lock whos constructor locks and destructor unlocks the mutex: