Boost logo

Boost :

From: Axter (boost_at_[hidden])
Date: 2005-05-29 17:53:00

> Axter wrote:
>> Is there any interest in adding to the boost library a synchronized
> pointer class which is a thread safe wrapper class for an object instance.
>> If so, please examine the following source code, and please post
>> feedback.
> I have a similar utility I use (see attached). But it rather shorter,
> code wise. How is your's different from the simpler approach of:
> monitor< std::vector<int> > my_vector;
> {
> monitor< std::vector<int> >::scoped_lock(my_vector) v;
> v->push_back(1);
> std::cout << (*v)[0] << '\n';
> }
> ??
> Obviously I'd be interested in seeing something like this in Boost ;-)

That's a very good method too.
However, it doesn't have the extra logic so that it can be used with an
implicit lock.
The sync_ptr class can lock implicitly like the following:
Or it can lock explicitly:
sync_ptr<vector<int> >::RefLock v = my_vector.get_locked_obj();

The implicit lock is good for single line access.
The explicit lock is a better choice when accessing the object multiple
lines of code, in which one call depends on the state of another call.
sync_ptr<vector<int> >::RefLock v = my_vector.get_locked_obj();
if (v->size() > 0) v->pop_back();

Your monitor class could easily be modified to use the implicit lock.

The sync_ptr method might be a little easier to use with abstract pointers.
Also, the syn_ptr.h header has a sync_ref_ptr class, which is a reference
counting pointer.
I think it would be difficult to add reference counting to the monitor
class. However, since you're actually storing a concrete type in the
monitor class, it might not be all that important to need the reference
counting feature.
The sync_ptr class also uses a template for the mutex class, so you can use
different types of synchroniztion methods (critical-section, mutex, atomic,
boost::mutex, etc...).

I propose both methods be included.
I like to add a modified version of your method to the sync_ptr header, and
call it sync_obj if you don't mind.

Boost list run by bdawes at, gregod at, cpdaniel at, john at