milvus/pkg/util/lifetime/safe_chan.go
congqixia af5c01082b
Refine delegator lifetime control (#26881)
- Add SafeChan interface in lifetime package
- Embed SafeChan into  interface
- Replace private lifetime struct in delegator package with
- Refine delegator on-going task lifetime control and wait all accepted task done
- Fix potential goroutine leakage from  if delegator closed concurrently

/kind improvement

Signed-off-by: Congqi Xia <congqi.xia@zilliz.com>
2023-09-07 10:11:15 +08:00

46 lines
793 B
Go

package lifetime
import (
"sync"
"github.com/milvus-io/milvus/pkg/util/typeutil"
)
// SafeChan is the utility type combining chan struct{} & sync.Once.
// It provides double close protection internally.
type SafeChan interface {
IsClosed() bool
CloseCh() <-chan struct{}
Close()
}
type safeChan struct {
closed chan struct{}
once sync.Once
}
// NewSafeChan returns a SafeChan with internal channel initialized
func NewSafeChan() SafeChan {
return newSafeChan()
}
func newSafeChan() *safeChan {
return &safeChan{
closed: make(chan struct{}),
}
}
func (sc *safeChan) CloseCh() <-chan struct{} {
return sc.closed
}
func (sc *safeChan) IsClosed() bool {
return typeutil.IsChanClosed(sc.closed)
}
func (sc *safeChan) Close() {
sc.once.Do(func() {
close(sc.closed)
})
}