fix: panic due to send on closed channel (close #5729)

This commit is contained in:
Andy Hsu 2024-01-05 11:40:44 +08:00
parent 9d5fb7f595
commit 8020d42b10

View File

@ -450,15 +450,19 @@ type Buf struct {
ctx context.Context ctx context.Context
off int off int
rw sync.RWMutex rw sync.RWMutex
notify chan struct{} //notify chan struct{}
} }
// NewBuf is a buffer that can have 1 read & 1 write at the same time. // NewBuf is a buffer that can have 1 read & 1 write at the same time.
// when read is faster write, immediately feed data to read after written // when read is faster write, immediately feed data to read after written
func NewBuf(ctx context.Context, maxSize int, id int) *Buf { func NewBuf(ctx context.Context, maxSize int, id int) *Buf {
d := make([]byte, 0, maxSize) d := make([]byte, 0, maxSize)
return &Buf{ctx: ctx, buffer: bytes.NewBuffer(d), size: maxSize, notify: make(chan struct{})} return &Buf{
ctx: ctx,
buffer: bytes.NewBuffer(d),
size: maxSize,
//notify: make(chan struct{}),
}
} }
func (br *Buf) Reset(size int) { func (br *Buf) Reset(size int) {
br.buffer.Reset() br.buffer.Reset()
@ -495,8 +499,8 @@ func (br *Buf) Read(p []byte) (n int, err error) {
select { select {
case <-br.ctx.Done(): case <-br.ctx.Done():
return 0, br.ctx.Err() return 0, br.ctx.Err()
case <-br.notify: //case <-br.notify:
return 0, nil // return 0, nil
case <-time.After(time.Millisecond * 200): case <-time.After(time.Millisecond * 200):
return 0, nil return 0, nil
} }
@ -510,12 +514,12 @@ func (br *Buf) Write(p []byte) (n int, err error) {
defer br.rw.Unlock() defer br.rw.Unlock()
n, err = br.buffer.Write(p) n, err = br.buffer.Write(p)
select { select {
case br.notify <- struct{}{}: //case br.notify <- struct{}{}:
default: default:
} }
return return
} }
func (br *Buf) Close() { func (br *Buf) Close() {
close(br.notify) //close(br.notify)
} }