Skip to content

Commit

Permalink
Broadcast notify on Buffer.Close
Browse files Browse the repository at this point in the history
  • Loading branch information
edaniels committed Jul 22, 2024
1 parent 51070b2 commit 882443d
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 4 deletions.
5 changes: 1 addition & 4 deletions packetio/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,10 +287,7 @@ func (b *Buffer) Close() (err error) {
b.mutex.Unlock()

if waiting {
select {
case b.notify <- struct{}{}:
default:
}
close(b.notify)
}

return nil
Expand Down
44 changes: 44 additions & 0 deletions packetio/buffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -582,3 +582,47 @@ func BenchmarkBuffer140(b *testing.B) {
func BenchmarkBuffer1400(b *testing.B) {
benchmarkBuffer(b, 1400)
}

func TestBufferConcurrentRead(t *testing.T) {
assert := assert.New(t)

buffer := NewBuffer()
packet := make([]byte, 4)

// Write twice
n, err := buffer.Write([]byte{2, 3, 4})
assert.NoError(err)
assert.Equal(3, n)

n, err = buffer.Write([]byte{5, 6, 7})
assert.NoError(err)
assert.Equal(3, n)

// Read twice
n, err = buffer.Read(packet)
assert.NoError(err)
assert.Equal(3, n)
assert.Equal([]byte{2, 3, 4}, packet[:n])

n, err = buffer.Read(packet)
assert.NoError(err)
assert.Equal(3, n)
assert.Equal([]byte{5, 6, 7}, packet[:n])

errCh := make(chan error, 2)
readIntoErr := func() {
_, readErr := buffer.Read(packet)
errCh <- readErr
}
go readIntoErr()
go readIntoErr()

// Close
err = buffer.Close()
assert.NoError(err)

err = <-errCh
assert.Equal(io.EOF, err)
err = <-errCh
assert.Equal(io.EOF, err)
}

0 comments on commit 882443d

Please sign in to comment.