OLD | NEW |
| (Empty) |
1 // Copyright (c) 2011 The Native Client 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. | |
4 | |
5 #ifndef THREAD_SAFE_REF_COUNT_H | |
6 #define THREAD_SAFE_REF_COUNT_H | |
7 | |
8 #include <pthread.h> | |
9 #include <cassert> | |
10 | |
11 const int kPthreadMutexSuccess = 0; | |
12 | |
13 namespace { | |
14 // Some synchronization helper classes. | |
15 | |
16 class ScopedLock { | |
17 public: | |
18 explicit ScopedLock(pthread_mutex_t* mutex) | |
19 : mutex_(mutex) { | |
20 if (pthread_mutex_lock(mutex_) != kPthreadMutexSuccess) { | |
21 mutex_ = NULL; | |
22 } | |
23 } | |
24 ~ScopedLock() { | |
25 if (mutex_ != NULL) { | |
26 pthread_mutex_unlock(mutex_); | |
27 } | |
28 } | |
29 private: | |
30 ScopedLock& operator=(const ScopedLock&); // Not implemented, do not use. | |
31 ScopedLock(const ScopedLock&); // Not implemented, do not use. | |
32 pthread_mutex_t* mutex_; // Weak reference, passed in to constructor. | |
33 }; | |
34 | |
35 class ThreadSafeRefCount { | |
36 public: | |
37 ThreadSafeRefCount() | |
38 : ref_(0) { | |
39 Init(); | |
40 } | |
41 | |
42 void Init() { | |
43 pthread_mutex_init(&mutex_, NULL); | |
44 } | |
45 | |
46 int32_t AddRef() { | |
47 ScopedLock s(&mutex_); | |
48 return ++ref_; | |
49 } | |
50 | |
51 int32_t Release() { | |
52 ScopedLock s(&mutex_); | |
53 return --ref_; | |
54 } | |
55 | |
56 private: | |
57 int32_t ref_; | |
58 pthread_mutex_t mutex_; | |
59 }; | |
60 | |
61 } // namespace | |
62 #endif // THREAD_SAFE_REF_COUNT_H | |
63 | |
OLD | NEW |