Boost logo

Boost Users :

From: Steven Woody (narkewoody_at_[hidden])
Date: 2007-10-04 11:05:44


On 10/4/07, KSpam <keesling_spam_at_[hidden]> wrote:
> Woody,
>
> All you have to do is protect the shared data with a boost::mutex. You will
> want to protect any methods that access or mutate the data. Boost has a
> nice "scoped_lock". The scoped_lock will set a lock and automatically unset
> the lock when it goes out of scope. If multiple threads reach this code, the
> first thread will set the lock and the other threads will wait until the lock
> is unset. This effectively makes the section of code protected by a
> scoped_lock single threaded. Here is a quick-and-dirty example:
>
> class ThreadSafeData
> {
> public:
> typedef std::vector<float> FloatVector;
>
> // Accessor (return by value)
> FloatVector getFloats (void) const
> {
> boost::mutex::scoped_lock lock(m_Mutex);
> return m_Floats;
> }
>
> // Mutator
> void addFloat (float value)
> {
> boost::mutex::scoped_lock lock(m_Mutex);
> m_Floats.push_back(value);
> }
>
> // Mutator
> void clearFloats (void)
> {
> boost::mutex::scoped_lock lock(m_Mutex);
> m_Floats.clear();
> }
>
> private:
> boost::mutex m_Mutex;
> FloatVector m_Floats;
> }
>
> Notice I am returning data by value instead of const reference! You do not
> want multiple threads keeping references around to shared data. Also, notice
> that this code does not concern itself with how the threads are created. It
> simply takes care of protecting the data from multiple threads (however they
> are created).
>
> I hope that this helps!
>
> Justin
>

thanks a lot for your code which cleared most of my question. while
the scoped_lock can has a thread block when a mutex object is being
locked by another thread, can you show me additional example about how
to let a thread immediately exit when it found a mutex object is being
used? i mean that one of thread in our application is actually the
GUI main thread, it will access the shared data in it's OnIdel event
handler, so i hope it will be never blocked, when resources are not
available, i hope it can immediately exist and try again some times
later. does the boost support this kind of feature? thanks.

-
woody


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net