Skip to content

Commit

Permalink
internal/mux: bug fix: race condition on the temporary buffers
Browse files Browse the repository at this point in the history
  • Loading branch information
hajimehoshi committed Dec 23, 2024
1 parent b2e2cd5 commit b1d8c7c
Showing 1 changed file with 27 additions and 8 deletions.
35 changes: 27 additions & 8 deletions internal/mux/mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ type playerImpl struct {
volume float64
err error
state playerState
tmpbuf []byte
bufPool *sync.Pool
buf []byte
eof bool
bufferSize int
Expand Down Expand Up @@ -246,15 +246,32 @@ func (p *playerImpl) setBufferSize(bufferSize int) {
p.bufferSize = p.mux.defaultBufferSize()
}
if orig != p.bufferSize {
p.tmpbuf = nil
p.bufPool = &sync.Pool{
New: func() interface{} {
buf := make([]byte, p.bufferSize)
return &buf
},
}
}
}

func (p *playerImpl) ensureTmpBuf() []byte {
if p.tmpbuf == nil {
p.tmpbuf = make([]byte, p.bufferSize)
func (p *playerImpl) getTmpBuf() ([]byte, func()) {
// The returned buffer could be accessed regardless of the mutex m (#254).
// In order to oavoid races, use a sync.Pool.
// On the other hand, the calls of getTmpBuf itself should be protected by the mutex m,
// then accessing p.bufPool doesn't cause races.
if p.bufPool == nil {
p.bufPool = &sync.Pool{
New: func() interface{} {
buf := make([]byte, p.bufferSize)
return &buf
},
}
}
buf := p.bufPool.Get().(*[]byte)
return *buf, func() {
p.bufPool.Put(buf)
}
return p.tmpbuf
}

// read reads the source to buf.
Expand Down Expand Up @@ -296,7 +313,8 @@ func (p *playerImpl) playImpl() {
p.state = playerPlay

if !p.eof {
buf := p.ensureTmpBuf()
buf, free := p.getTmpBuf()
defer free()
for len(p.buf) < p.bufferSize {
n, err := p.read(buf)
if err != nil && err != io.EOF {
Expand Down Expand Up @@ -525,7 +543,8 @@ func (p *playerImpl) readSourceToBuffer() int {
return 0
}

buf := p.ensureTmpBuf()
buf, free := p.getTmpBuf()
defer free()
n, err := p.read(buf)

if err != nil && err != io.EOF {
Expand Down

0 comments on commit b1d8c7c

Please sign in to comment.