Skip to content

Commit

Permalink
Use defer to unlock mutex
Browse files Browse the repository at this point in the history
  • Loading branch information
erni27 committed Apr 5, 2023
1 parent 38b7341 commit 504f784
Showing 1 changed file with 3 additions and 7 deletions.
10 changes: 3 additions & 7 deletions internal/buffer/unbounded.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,29 +48,27 @@ func NewUnbounded() *Unbounded {
// Put adds t to the unbounded buffer.
func (b *Unbounded) Put(t interface{}) {
b.mu.Lock()
defer b.mu.Unlock()
if b.closed {
b.mu.Unlock()
return
}
if len(b.backlog) == 0 {
select {
case b.c <- t:
b.mu.Unlock()
return
default:
}
}
b.backlog = append(b.backlog, t)
b.mu.Unlock()
}

// Load sends the earliest buffered data, if any, onto the read channel
// returned by Get(). Users are expected to call this every time they read a
// value from the read channel.
func (b *Unbounded) Load() {
b.mu.Lock()
defer b.mu.Unlock()
if b.closed {
b.mu.Unlock()
return
}
if len(b.backlog) > 0 {
Expand All @@ -81,7 +79,6 @@ func (b *Unbounded) Load() {
default:
}
}
b.mu.Unlock()
}

// Get returns a read channel on which values added to the buffer, via Put(),
Expand All @@ -97,11 +94,10 @@ func (b *Unbounded) Get() <-chan interface{} {
// Close closes the unbounded buffer.
func (b *Unbounded) Close() {
b.mu.Lock()
defer b.mu.Unlock()
if b.closed {
b.mu.Unlock()
return
}
b.closed = true
close(b.c)
b.mu.Unlock()
}

0 comments on commit 504f784

Please sign in to comment.