Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is an old version of boost. Click here for the latest version's documentation home page.
C++ Boost

guard - Auto-lock/unlock-er

Introduction

detail/guard.hpp provides a type guard<Mutex> that allows scoped access to the Mutex's locking and unlocking operations. It is used to ensure that a Mutex is unlocked, even if an exception is thrown.

Synopsis

namespace details {
namespace pool {

template <typename Mutex>
class guard
{
  private:
    guard(const guard &);
    void operator=(const guard &);

  public:
    explicit guard(Mutex & mtx);
    ~guard();
};

} // namespace pool
} // namespace details

Semantics

Symbol Table
SymbolMeaning
Tguard<Mutex>
mvalue of type Mutex &
gvalue of type guard<Mutex>

Requirements on Mutex
ExpressionReturn TypeAssertion/Note/Pre/Post-Condition
m.lock()not usedLocks the mutex referred to by m
m.unlock()not usedUnlocks the mutex referred to by m

Requirements satisfied by guard
ExpressionAssertion/Note/Pre/Post-Condition
T(m)Locks the mutex referred to by m; binds T(m) to m
(&g)->~T()Unlocks the mutex that g is bound to

Example

Given a (platform-specific) mutex class, we can wrap code as follows:

extern mutex global_lock;

static void f()
{
  boost::details::pool::guard<mutex> g(global_lock);
  // g's constructor locks "global_lock"

  ... // do anything:
      //   throw exceptions
      //   return
      //   or just fall through
} // g's destructor unlocks "global_lock"

Dependencies

None.

Future Directions

This header will eventually be replaced by a Boost multithreading library.


Copyright © 2000, 2001 Stephen Cleary (scleary AT jerviswebb DOT com)

This file can be redistributed and/or modified under the terms found in copyright.html

This software and its documentation is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.