Skip to content

Commit 20be255

Browse files
committed
添加 CountDownLatch
添加 CountDownLatch, 批量等待多个Coroutine结束
1 parent 4780002 commit 20be255

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

libgo/coroutine.h

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#pragma once
22
#define __const__
3+
#include <atomic>
34
#include "common/config.h"
45
#include "common/pp.h"
56
#include "common/syntax_helper.h"
@@ -71,3 +72,29 @@ typedef ::co::CoTimer::TimerId co_timer_id;
7172
#define co_last_defer() ::co::GetLastDefer()
7273
#define co_defer_scope co_defer [&]
7374

75+
class CountDownLatch {
76+
public:
77+
explicit CountDownLatch(size_t n = 1) : mFlyingCount(n) {}
78+
79+
void Add(size_t i) {
80+
mFlyingCount += i;
81+
}
82+
83+
void Done() {
84+
if (--mFlyingCount == 0) {
85+
ch_0.Close();
86+
}
87+
}
88+
void Wait() {
89+
int done;
90+
ch_0 >> done;
91+
}
92+
private:
93+
std::atomic<size_t> mFlyingCount;
94+
co_chan<int> ch_0;
95+
96+
CountDownLatch(CountDownLatch const &) = delete;
97+
CountDownLatch(CountDownLatch &&) = delete;
98+
CountDownLatch& operator=(CountDownLatch const &) = delete;
99+
CountDownLatch& operator=(CountDownLatch &&) = delete;
100+
};

0 commit comments

Comments
 (0)