Boost logo

Boost Users :

From: bill_kempf (williamkempf_at_[hidden])
Date: 2002-07-19 13:43:21


--- In Boost-Users_at_y..., Herve Blanc <blanc_at_s...> wrote:
> Is there anything available or coming in boost::thread to wrap STL
containers
> into thread safe containers?

No.

> If not, any advice for coding those wrappers efficiently/elegantly
or not doing
> that?

Trying to do this is generally a bad idea. Using an internal mutex
to protect the class will only allow you to synchronize at the method
call level, and most user code will need synchronization around
multiple such calls not a single call. Example:

my_thread_safe_vector[0] += some_value;
if (my_thread_safe_vector[0] > 100)
   my_thread_safe_vector[0] = 100;

The above code is full of race conditions, even if
my_thread_safe_vector uses a mutex internally.

> If not again, why and how do you deal with the problem then?

Use an external mutex to achieve the proper lock granularity.
Example:

boost::mutex::scoped_lock lock(my_mutex);
my_vector[0] += some_value;
if (my_vector[0] > 100)
   my_vector[0] = 100;

There's no race in the above since the external mutex and lock insure
the proper granularity for the three calls to the container methods.

Bill Kempf


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