-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshutdownctrl.go
50 lines (41 loc) · 1018 Bytes
/
shutdownctrl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package xhttp
import (
"context"
"sync"
"sync/atomic"
)
var shutdownController = NewShutdownController()
type ShutdownController struct {
shutdownFlag int32 // 原子标记,表示是否进入停机状态
waitGroup sync.WaitGroup // 用于等待所有处理中的请求完成
}
func NewShutdownController() *ShutdownController {
return &ShutdownController{}
}
func (sc *ShutdownController) BeginRequest() bool {
if atomic.LoadInt32(&sc.shutdownFlag) == 1 {
return false
}
sc.waitGroup.Add(1)
return true
}
func (sc *ShutdownController) EndRequest() {
sc.waitGroup.Done()
}
func (sc *ShutdownController) InitiateShutdown(ctx context.Context) {
atomic.StoreInt32(&sc.shutdownFlag, 1)
done := make(chan struct{})
go func() {
sc.waitGroup.Wait()
close(done)
}()
select {
case <-ctx.Done(): // Timeout or ctx canceled, stop waiting.
return
case <-done: // waitGroup has completed
return
}
}
func Shutdown(ctx context.Context) {
shutdownController.InitiateShutdown(ctx)
}