Skip to content

Commit

Permalink
fix: Switch atomic.Value to atomicBool (taken from Go 1.19 stdlib)
Browse files Browse the repository at this point in the history
  • Loading branch information
jameshoulahan authored and LBeernaertProton committed Sep 8, 2022
1 parent 07462bd commit 70c0cb9
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
24 changes: 24 additions & 0 deletions internal/queue/bool.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package queue

import "sync/atomic"

// atomicBool is an atomic boolean value.
// The zero value is false.
type atomicBool struct {
v uint32
}

// Load atomically loads and returns the value stored in x.
func (x *atomicBool) load() bool { return atomic.LoadUint32(&x.v) != 0 }

// Store atomically stores val into x.
func (x *atomicBool) store(val bool) { atomic.StoreUint32(&x.v, b32(val)) }

// b32 returns a uint32 0 or 1 representing b.
func b32(b bool) uint32 {
if b {
return 1
}

return 0
}
11 changes: 5 additions & 6 deletions internal/queue/queued_channel.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package queue

import (
"sync"
"sync/atomic"
)

// QueuedChannel represents a channel on which queued items can be published without having to worry if the reader
Expand All @@ -12,7 +11,7 @@ type QueuedChannel[T any] struct {
ch chan T
items []T
cond *sync.Cond
closed atomic.Value // Should use atomic.Bool once we use Go 1.19.
closed atomicBool // Should use atomic.Bool once we use Go 1.19!
}

func NewQueuedChannel[T any](chanBufferSize, queueCapacity int) *QueuedChannel[T] {
Expand All @@ -23,7 +22,7 @@ func NewQueuedChannel[T any](chanBufferSize, queueCapacity int) *QueuedChannel[T
}

// The queue is initially not closed.
queue.closed.Store(false)
queue.closed.store(false)

go func() {
defer close(queue.ch)
Expand All @@ -42,7 +41,7 @@ func NewQueuedChannel[T any](chanBufferSize, queueCapacity int) *QueuedChannel[T
}

func (q *QueuedChannel[T]) Enqueue(items ...T) bool {
if q.closed.Load().(bool) {
if q.closed.load() {
return false
}

Expand All @@ -61,7 +60,7 @@ func (q *QueuedChannel[T]) GetChannel() <-chan T {
}

func (q *QueuedChannel[T]) Close() {
q.closed.Store(true)
q.closed.store(true)

q.cond.L.Lock()
defer q.cond.L.Unlock()
Expand All @@ -79,7 +78,7 @@ func (q *QueuedChannel[T]) pop() (T, bool) {
// This allows the queue to continue popping elements if it's closed,
// but will prevent it from hanging indefinitely once it runs out of items.
for len(q.items) == 0 {
if q.closed.Load().(bool) {
if q.closed.load() {
return item, false
}

Expand Down

0 comments on commit 70c0cb9

Please sign in to comment.