2023-10-05 04:11:12 +08:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
type SafeChannel struct {
|
2024-01-24 07:20:16 +08:00
|
|
|
ch chan interface{}
|
|
|
|
closed bool
|
|
|
|
mux sync.Mutex
|
|
|
|
freezeFlag bool
|
2023-10-05 04:11:12 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewSafeChannel(size int) *SafeChannel {
|
|
|
|
return &SafeChannel{
|
|
|
|
ch: make(chan interface{}, size),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SafeChannel) Send(value interface{}) bool {
|
|
|
|
s.mux.Lock()
|
|
|
|
defer s.mux.Unlock()
|
|
|
|
|
|
|
|
if s.closed {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
s.ch <- value
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SafeChannel) Receive() (interface{}, bool) {
|
|
|
|
val, ok := <-s.ch
|
|
|
|
return val, ok
|
|
|
|
}
|
|
|
|
|
2023-12-15 01:01:47 +08:00
|
|
|
func (s *SafeChannel) ReceiveChannel() <-chan interface{} {
|
|
|
|
return s.ch
|
|
|
|
}
|
|
|
|
|
2023-10-05 04:11:12 +08:00
|
|
|
func (s *SafeChannel) Close() {
|
|
|
|
s.mux.Lock()
|
|
|
|
defer s.mux.Unlock()
|
|
|
|
|
|
|
|
if !s.closed {
|
|
|
|
close(s.ch)
|
|
|
|
s.closed = true
|
|
|
|
}
|
|
|
|
}
|
2024-01-24 07:20:16 +08:00
|
|
|
|
|
|
|
func (s *SafeChannel) FreezeChannel() {
|
|
|
|
if !s.freezeFlag {
|
|
|
|
s.mux.Lock()
|
|
|
|
s.freezeFlag = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SafeChannel) UnfreezeChannel() {
|
|
|
|
if s.freezeFlag {
|
|
|
|
s.mux.Unlock()
|
|
|
|
s.freezeFlag = false
|
|
|
|
}
|
|
|
|
}
|