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_CONDITION_H_ | |
6 #define THREAD_CONDITION_H_ | |
7 | |
8 #include "threading/pthread_ext.h" | |
9 | |
10 namespace threading { | |
11 // A wrapper class for condition signaling. Contains a mutex and condition | |
12 // pair. | |
13 class ThreadCondition { | |
14 public: | |
15 // Initialize the mutex and the condition. | |
16 ThreadCondition() { | |
17 pthread_mutex_init(&cond_mutex_, NULL); | |
18 pthread_cond_init(&condition_, NULL); | |
19 } | |
20 | |
21 virtual ~ThreadCondition() { | |
22 pthread_cond_destroy(&condition_); | |
23 pthread_mutex_destroy(&cond_mutex_); | |
24 } | |
25 | |
26 // Lock the mutex, do this before signalling the condition. | |
27 void Lock() { | |
28 pthread_mutex_lock(&cond_mutex_); | |
29 } | |
30 | |
31 // Unlock the mutex, do this after raising a signal or after returning from | |
32 // Wait(). | |
33 void Unlock() { | |
34 pthread_mutex_unlock(&cond_mutex_); | |
35 } | |
36 | |
37 // Signal the condition. This will cause Wait() to return. | |
38 void Signal() { | |
39 pthread_cond_broadcast(&condition_); | |
40 } | |
41 | |
42 // Wait for a Signal(). Note that this can spuriously return, so you should | |
43 // have a guard bool to see if the condtion is really true. E.g., in the | |
44 // calling thread: | |
45 // cond_lock->Lock(); | |
46 // cond_true = true; | |
47 // cond_lock->Signal(); | |
48 // cond_lock->Unlock(); | |
49 // In the worker thread: | |
50 // cond_lock->Lock(); | |
51 // while (!cond_true) { | |
52 // cond_lock->Wait(); | |
53 // } | |
54 void Wait() { | |
55 pthread_cond_wait(&condition_, &cond_mutex_); | |
56 } | |
57 | |
58 // Same as Wait, but wait at most until abs_time. Returns false if the system | |
59 // time exceeds abs_time before the condition is signaled. | |
60 bool TimedWait(struct timespec *abs_time) { | |
61 return (pthread_cond_timedwait(&condition_, &cond_mutex_, abs_time) == 0); | |
62 } | |
63 | |
64 private: | |
65 pthread_mutex_t cond_mutex_; | |
66 pthread_cond_t condition_; | |
67 }; | |
68 } // namespace threading | |
69 | |
70 #endif // THREAD_CONDITION_H_ | |
OLD | NEW |