|
|
Boost.Threadsbasic_lock |
Introduction
Header
Synopsis
Members
Example
This class template defines a generic lock
concept type. The mutex, try_mutex,
timed_mutex, recursive_mutex,
recursive_try_mutex and recursive_timed_mutex
classes all use this template to define their lock types. Instances of class basic_lock
meet the Lock requirements.
Like all the Boost.Threads lock models, basic_lock objects are meant to be short lived. Objects of class basic_lock are not thread-safe, and so should not be shared between threads.
Class basic_lock follows the "resource acquisition is initialization" idiom [Stroustrup 00 14.4.1] and is a realization of the "Scoped Locking Pattern" [Schmidt-00]. Thus the usage is to let the constructor do the locking, and then let the destructor do the unlocking automatically at the end of the enclosing scope. The lock() and unlock() members are commonly not explicitly called, but allow for complex overlapping locks of multiple Mutex concepts.
The type M used to instantiate class basic_lock
must meet the Mutex requirements.
#include <boost/thread/xlock.hpp>
This header is usually not included directly by programmers
because it is supplied by <boost/thread/mutex.hpp> or
<boost/thread/recursive_mutex.hpp>
namespace boost {
template <typename M>
class basic_lock : private boost::noncopyable
{
public:
typedef M mutex_type;
explicit basic_lock(M& mx, bool lock_it=true);
~basic_lock();
void lock();
void unlock();
operator const void*() const;
};
} // namespace boost
explicit basic_lock(M& mx, bool lock_it=true);
Effects: Associates mutex mx with *this.
If lock_it is true, then calls lock().
~basic_lock();
Effects: If locked calls unlock(), then destroys *this.
void lock();
Requires: this->operator const void*() == 0 (not locked).
Effects: Attempts to lock the associated mutex. If the associated mutex is already locked by the currently running thread the effects depend on the locking strategy of the associated mutex, as shown in the following table:
| Locking Strategy of associated mutex |
Effect if associated mutex is already locked |
| Recursive | As if an additional lock were added to the mutex. |
| Checked | Throws lock_error. |
| Unspecified | Undefined behavior [ISO 1.3.12] (but typically, deadlock.) |
Throws: lock_error if the lock object is already locked or if the associated mutex uses the Checked Locking Strategy and has already been locked by the currently running thread.
void unlock();
Effects: Unlocks the associated mutex.
Throws: lock_error if the associated mutex is not already locked.
operator const void*() const;
Returns: If the associated mutex is currently locked, a value
convertible to true, else a value convertible to false.
Rationale: A const void* conversion is considered safer
than a conversion to bool.
See the example given in the documentation for the mutex class.
Revised 19 July, 2001
Copyright William E. Kempf 2001 all rights reserved.