ipc/chromium/src/base/lock.h

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/ipc/chromium/src/base/lock.h	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,75 @@
     1.4 +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
     1.5 +// Use of this source code is governed by a BSD-style license that can be
     1.6 +// found in the LICENSE file.
     1.7 +
     1.8 +#ifndef BASE_LOCK_H_
     1.9 +#define BASE_LOCK_H_
    1.10 +
    1.11 +#include "base/lock_impl.h"
    1.12 +
    1.13 +// A convenient wrapper for an OS specific critical section.
    1.14 +
    1.15 +class Lock {
    1.16 + public:
    1.17 +  Lock() : lock_() {}
    1.18 +  ~Lock() {}
    1.19 +  void Acquire() { lock_.Lock(); }
    1.20 +  void Release() { lock_.Unlock(); }
    1.21 +  // If the lock is not held, take it and return true. If the lock is already
    1.22 +  // held by another thread, immediately return false.
    1.23 +  bool Try() { return lock_.Try(); }
    1.24 +
    1.25 +  // In debug builds this method checks that the lock has been acquired by the
    1.26 +  // calling thread.  If the lock has not been acquired, then the method
    1.27 +  // will DCHECK().  In non-debug builds, the LockImpl's implementation of
    1.28 +  // AssertAcquired() is an empty inline method.
    1.29 +  void AssertAcquired() const { return lock_.AssertAcquired(); }
    1.30 +
    1.31 +  // Return the underlying lock implementation.
    1.32 +  // TODO(awalker): refactor lock and condition variables so that this is
    1.33 +  // unnecessary.
    1.34 +  LockImpl* lock_impl() { return &lock_; }
    1.35 +
    1.36 + private:
    1.37 +  LockImpl lock_;  // Platform specific underlying lock implementation.
    1.38 +
    1.39 +  DISALLOW_COPY_AND_ASSIGN(Lock);
    1.40 +};
    1.41 +
    1.42 +// A helper class that acquires the given Lock while the AutoLock is in scope.
    1.43 +class AutoLock {
    1.44 + public:
    1.45 +  explicit AutoLock(Lock& lock) : lock_(lock) {
    1.46 +    lock_.Acquire();
    1.47 +  }
    1.48 +
    1.49 +  ~AutoLock() {
    1.50 +    lock_.AssertAcquired();
    1.51 +    lock_.Release();
    1.52 +  }
    1.53 +
    1.54 + private:
    1.55 +  Lock& lock_;
    1.56 +  DISALLOW_COPY_AND_ASSIGN(AutoLock);
    1.57 +};
    1.58 +
    1.59 +// AutoUnlock is a helper that will Release() the |lock| argument in the
    1.60 +// constructor, and re-Acquire() it in the destructor.
    1.61 +class AutoUnlock {
    1.62 + public:
    1.63 +  explicit AutoUnlock(Lock& lock) : lock_(lock) {
    1.64 +    // We require our caller to have the lock.
    1.65 +    lock_.AssertAcquired();
    1.66 +    lock_.Release();
    1.67 +  }
    1.68 +
    1.69 +  ~AutoUnlock() {
    1.70 +    lock_.Acquire();
    1.71 +  }
    1.72 +
    1.73 + private:
    1.74 +  Lock& lock_;
    1.75 +  DISALLOW_COPY_AND_ASSIGN(AutoUnlock);
    1.76 +};
    1.77 +
    1.78 +#endif  // BASE_LOCK_H_

mercurial