Skip to content

Commit 4737dcd

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

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-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 Done() {
80+
--mFlyingCount;
81+
}
82+
void Wait() {
83+
uint64_t usec = 100 * 1000;
84+
while (mFlyingCount) {
85+
if (co_sched.TaskCount() <= co_sched.ProcessCount()) {
86+
usleep(usec);
87+
usec <<= 1;
88+
} else {
89+
co_yield;
90+
}
91+
}
92+
}
93+
private:
94+
std::atomic<size_t> mFlyingCount;
95+
96+
CountDownLatch(CountDownLatch const &) = delete;
97+
CountDownLatch(CountDownLatch &&) = delete;
98+
CountDownLatch& operator=(CountDownLatch const &) = delete;
99+
CountDownLatch& operator=(CountDownLatch &&) = delete;
100+
};

libgo/scheduler/scheduler.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,9 @@ class Scheduler
5656
// 使用独立的定时器线程
5757
void UseAloneTimerThread();
5858

59+
// 当前调度器中的线程数量
60+
size_t ProcessCount() { return processers_.size(); };
61+
5962
// 当前调度器中的协程数量
6063
uint32_t TaskCount();
6164

0 commit comments

Comments
 (0)