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