Nebula
Loading...
Searching...
No Matches
linuxcompletioncounter.h
Go to the documentation of this file.
1#pragma once
2//----------------------------------------------------------------------------------------
11#include "core/types.h"
12
13//----------------------------------------------------------------------------------------
14namespace Linux
15{
17{
18public:
23
25 void Reset(int count);
27 bool Decrement(int num);
29 void Wait();
31 bool Peek();
32
33private:
34 volatile int curCount;
35 pthread_cond_t completionEvent;
36};
37
38//----------------------------------------------------------------------------------------
41inline
43 curCount(0)
44{
45 // create a manual-reset event, and initially in signalled state
46 pthread_cond_init(&this->completionEvent, 0);
47}
48
49//----------------------------------------------------------------------------------------
52inline
54{
55 pthread_cond_destroy(&this->completionEvent);
56}
57
58//----------------------------------------------------------------------------------------
64inline void
66{
67 n_assert(count > 0);
68 n_assert(0 == this->curCount);
69 this->curCount = count;
70}
71
72//----------------------------------------------------------------------------------------
78inline bool
80{
81 if (LinuxInterlocked::Add(this->curCount, -num) == num)
82 {
83 pthread_cond_signal(&this->completionEvent);
84 return true;
85 }
86 else
87 {
88 return false;
89 }
90}
91
92//----------------------------------------------------------------------------------------
98inline void
100{
101 pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
102 pthread_mutex_lock(&m);
103 while(this->curCount > 0)
104 {
105 pthread_cond_wait(&this->completionEvent, &m);
106 }
107 pthread_mutex_unlock(&m);
108 pthread_mutex_destroy(&m);
109}
110
111//----------------------------------------------------------------------------------------
115inline bool
117{
118 return (0 == this->curCount);
119}
120
121} // namespace Linux
122//----------------------------------------------------------------------------------------
Block a thread until count reaches 0.
Definition linuxcompletioncounter.h:17
void Reset(int count)
reset the counter, call from main thread
Definition linuxcompletioncounter.h:65
void Wait()
wait until counter has reached 0, call from main thread or worker threads
Definition linuxcompletioncounter.h:99
bool Peek()
check if the counter has reached 0
Definition linuxcompletioncounter.h:116
volatile int curCount
Definition linuxcompletioncounter.h:34
~LinuxCompletionCounter()
destructor
Definition linuxcompletioncounter.h:53
bool Decrement(int num)
decrement the counter, call from worker threads, return true if count has reached zero
Definition linuxcompletioncounter.h:79
LinuxCompletionCounter()
constructor
Definition linuxcompletioncounter.h:42
pthread_cond_t completionEvent
Definition linuxcompletioncounter.h:35
#define n_assert(exp)
Definition debug.h:50
Definition linuxcompletioncounter.h:15