|
Boost : |
From: Wayne Miller (wcm_at_[hidden])
Date: 2001-04-25 15:25:26
> From: williamkempf_at_[hidden]
> Using the const-ness of the object to distinguish between read and
> write locks is, IMHO, a very bad idea, especially since locking
> changes the object's state.
This feature is so that the lock may be used inside of const-member
functions of the object it is intended to protect.
class Monitor
{
int x;
ReaderWriter<MUTEX,SEMAPHORE> rw;
public:
int read() const
{
int result;
rw.lock(); // read lock automatically called.
result = x;
rw.unlock(); // read unlock automatically called.
}
void write(int y)
{
rw.lock(); // write lock automatically called.
x = y;
rw.unlock(); // write unlock automatically called.
}
}
Note that rw.lock() should generate an error in the first member function if
rw.lock() were not const.
A bonus is that the read_lock or write_lock is implied by the context, and
is always safe.
Also note that a single change of the line:
ReaderWriter<MUTEX,SEMAPHORE> rw;
to
MUTEX rw;
would still be safe, and "break" nothing. It would then be trivial for the
developer to profile both implementations.
> The lock is implemented as a template that takes two parameters, an
> object type SEMAPHORE, and an object type MUTEX. These are trivial objects
> that both must support the interface lock and unlock.
I could not think of a fully portable alternative. Even making a mutex class
out of pthread synchronization is not (fully) portable. However...
> - should use the structure and terminology of the draft Boost.Thread
> library...
Not sure where this is; can't seem to find it at boost.org. I don't mind
killing off the template and binding to the boost thread library mutex
specification.
> - should provide a (preferably non-trivial) demonstration program to
> show the usefulness
Sounds fair.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk