File tree Expand file tree Collapse file tree 4 files changed +70
-3
lines changed
Expand file tree Collapse file tree 4 files changed +70
-3
lines changed Original file line number Diff line number Diff line change @@ -153,3 +153,13 @@ x << c; //Receving from channel
153153
154154c.close(); //Closing the channel
155155```
156+
157+ ### WaitGroup
158+ ``` cpp
159+ Core::WaitGroup wg; // Creating a wait group
160+ wg.add() // adding to waitgroup adding 1 to counter
161+ wg.add(10 ) // adding to waitgroup adding 10 to counter
162+
163+ wg.done() // wait group is done and decrease counter by 1
164+ wg.wait() // wait for wait group to complete , ie counter becomes 0
165+ ```
Original file line number Diff line number Diff line change 1+ #ifndef WAITGROUP_H
2+ #define WAITGROUP_H
3+
4+ using namespace std ;
5+ namespace Core
6+ {
7+ class WaitGroup
8+ {
9+ mutex mMtx ;
10+ mutex mCondMtx ;
11+ condition_variable mCondVar ;
12+ unsigned int mCounter ;
13+ public:
14+ WaitGroup ()
15+ {
16+ mCounter = 0x00 ;
17+ }
18+ ~WaitGroup ()
19+ {
20+ }
21+
22+ void add (unsigned int delta = 1 )
23+ {
24+ lock_guard<mutex> lock (this ->mMtx );
25+ mCounter += delta;
26+ }
27+
28+ void done ()
29+ {
30+ lock_guard<mutex> lock (this ->mMtx );
31+ mCounter --;
32+ unique_lock<mutex> lockCondition (this ->mCondMtx );
33+ this ->mCondVar .notify_all ();
34+ }
35+
36+ void wait ()
37+ {
38+
39+ unique_lock<mutex> lock (this ->mCondMtx );
40+ this ->mCondVar .wait (lock, [&]{ return (!this ->mCounter ); });
41+
42+ }
43+
44+ unsigned int count ()
45+ {
46+ return mCounter ;
47+ }
48+ };
49+ }
50+
51+ #endif
Original file line number Diff line number Diff line change 66#include < timer/include/TimerTask.h>
77#include < ipc/include/MessageQueue.h>
88#include < core/include/Channel.h>
9+ #include < core/include/WaitGroup.h>
910
1011using namespace std ;
1112// unique_ptr<Core::Application> pApplication(new Core::Application());
@@ -90,18 +91,22 @@ void fn()
9091
9192int main ()
9293{
93-
94- for (int i = 0 ; i < 1000000 ; i++)
94+ Core::WaitGroup wg;
95+ for (int i = 0 ; i < 1000 ; i++)
9596 {
97+ wg.add ();
9698 c << rand () % 100 ;
9799 async ([&]()
98100 {
99101 int x ;
100102 x << c;
101103 cout <<" Got from channel " << x << " Channel size " << c.size ()<<endl;
104+ wg.done ();
102105 });
103- usleep (1000 );
106+ // usleep(1000);
104107 }
108+ cout<<" Wait counter " <<wg.count ()<<endl;
109+ wg.wait ();
105110 /*
106111 atexit(onExit);
107112
Original file line number Diff line number Diff line change 99#include < inttypes.h>
1010#include < dirent.h>
1111#include < fstream>
12+ #include < memory>
1213
1314#define LOG_CR 1
1415#define LOG_ER 2
You can’t perform that action at this time.
0 commit comments