mirror of
https://github.com/yusing/godoxy.git
synced 2026-04-10 19:27:07 +02:00
graceful shutdown and ref count related
This commit is contained in:
42
internal/utils/ref_count.go
Normal file
42
internal/utils/ref_count.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package utils
|
||||
|
||||
type RefCount struct {
|
||||
_ NoCopy
|
||||
|
||||
refCh chan bool
|
||||
notifyZero chan struct{}
|
||||
}
|
||||
|
||||
func NewRefCounter() *RefCount {
|
||||
rc := &RefCount{
|
||||
refCh: make(chan bool, 1),
|
||||
notifyZero: make(chan struct{}),
|
||||
}
|
||||
go func() {
|
||||
refCount := uint32(1)
|
||||
for isAdd := range rc.refCh {
|
||||
if isAdd {
|
||||
refCount++
|
||||
} else {
|
||||
refCount--
|
||||
}
|
||||
if refCount <= 0 {
|
||||
close(rc.notifyZero)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
return rc
|
||||
}
|
||||
|
||||
func (rc *RefCount) Zero() <-chan struct{} {
|
||||
return rc.notifyZero
|
||||
}
|
||||
|
||||
func (rc *RefCount) Add() {
|
||||
rc.refCh <- true
|
||||
}
|
||||
|
||||
func (rc *RefCount) Sub() {
|
||||
rc.refCh <- false
|
||||
}
|
||||
Reference in New Issue
Block a user