C
chsalvia
The design philosophy behind the boost Lock concept seems to be to
implement short-lived, tightly-scoped locks which automatically unlock
the mutex when they go out of scope. This design is nice because it
clears up all the pthread_mutex_lock/unlock clutter you find in code
that needs to unlock a mutex before leaving scope.
However, I find that sometimes you need to keep a mutex locked even
after the program proceeds beyond the current scope. For example, you
may have a class which contains a mutex as a member variable, and a
function which locks the mutex, and keeps it locked until a
corresponding unlock function is called.
But as far as I can tell, boost scoped_lock provides no real way to do
this. A scoped lock will automatically unlock the mutex once the
program returns from a function, and you can't have a scoped locked as
a member variable in an object that is shared between threads, because
locks are not thread safe. Therefore, if you want to achieve a
persistent lock, you need to pass your mutex directly to
lock_ops<mutex_type>::lock(). But this comes from the detail
namespace, and presumably should only be called by boost library code,
and not by developer code.
So, what is the best way to achieve a persistent lock using boost
locks?
implement short-lived, tightly-scoped locks which automatically unlock
the mutex when they go out of scope. This design is nice because it
clears up all the pthread_mutex_lock/unlock clutter you find in code
that needs to unlock a mutex before leaving scope.
However, I find that sometimes you need to keep a mutex locked even
after the program proceeds beyond the current scope. For example, you
may have a class which contains a mutex as a member variable, and a
function which locks the mutex, and keeps it locked until a
corresponding unlock function is called.
But as far as I can tell, boost scoped_lock provides no real way to do
this. A scoped lock will automatically unlock the mutex once the
program returns from a function, and you can't have a scoped locked as
a member variable in an object that is shared between threads, because
locks are not thread safe. Therefore, if you want to achieve a
persistent lock, you need to pass your mutex directly to
lock_ops<mutex_type>::lock(). But this comes from the detail
namespace, and presumably should only be called by boost library code,
and not by developer code.
So, what is the best way to achieve a persistent lock using boost
locks?