blob: 4bd27dcab9090b25d66a64a90ed63e9ed8baa34d [file] [log] [blame]
license.botf003cfe2008-08-24 09:55:55 +09001// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit3f4a7322008-07-27 06:49:38 +09004
mmentovai@google.comf5a40002008-08-09 01:19:43 +09005#ifndef BASE_LOCK_IMPL_H_
6#define BASE_LOCK_IMPL_H_
7
8#include "build/build_config.h"
9
10#if defined(OS_WIN)
11#include <windows.h>
12#elif defined(OS_POSIX)
13#include <pthread.h>
14#endif
initial.commit3f4a7322008-07-27 06:49:38 +090015
16#include "base/basictypes.h"
17
initial.commit3f4a7322008-07-27 06:49:38 +090018// This class implements the underlying platform-specific spin-lock mechanism
19// used for the Lock class. Most users should not use LockImpl directly, but
20// should instead use Lock.
21class LockImpl {
22 public:
mmentovai@google.comf5a40002008-08-09 01:19:43 +090023#if defined(OS_WIN)
24 typedef CRITICAL_SECTION OSLockType;
25#elif defined(OS_POSIX)
26 typedef pthread_mutex_t OSLockType;
27#endif
28
initial.commit3f4a7322008-07-27 06:49:38 +090029 LockImpl();
30 ~LockImpl();
31
32 // If the lock is not held, take it and return true. If the lock is already
33 // held by something else, immediately return false.
34 bool Try();
35
36 // Take the lock, blocking until it is available if necessary.
37 void Lock();
38
39 // Release the lock. This must only be called by the lock's holder: after
40 // a successful call to Try, or a call to Lock.
41 void Unlock();
42
mmentovai@google.comf5a40002008-08-09 01:19:43 +090043 // Return the native underlying lock.
44 // TODO(awalker): refactor lock and condition variables so that this is
45 // unnecessary.
46 OSLockType* os_lock() { return &os_lock_; }
initial.commit3f4a7322008-07-27 06:49:38 +090047
mmentovai@google.comf5a40002008-08-09 01:19:43 +090048 private:
49 OSLockType os_lock_;
50
51 DISALLOW_COPY_AND_ASSIGN(LockImpl);
initial.commit3f4a7322008-07-27 06:49:38 +090052};
53
54class AutoLockImpl {
55 public:
56 AutoLockImpl(LockImpl* lock_impl)
57 : lock_impl_(lock_impl) {
58 lock_impl_->Lock();
59 }
60
61 ~AutoLockImpl() {
62 lock_impl_->Unlock();
63 }
64
65 private:
66 DISALLOW_EVIL_CONSTRUCTORS(AutoLockImpl);
67
68 LockImpl* lock_impl_;
69};
70
mmentovai@google.comf5a40002008-08-09 01:19:43 +090071#endif // BASE_LOCK_IMPL_H_
license.botf003cfe2008-08-24 09:55:55 +090072