-
Notifications
You must be signed in to change notification settings - Fork 27
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Allows the user to queue items on a channel that may be blocked waiting for reads, without having to wait for those read to complete.
- Loading branch information
1 parent
15b3218
commit 5014519
Showing
2 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
package queue | ||
|
||
// QueuedChannel represents a channel on which queued items can be published without having to worry if the reader | ||
// has actually consumed existing items first or if there's no way of knowing ahead of time what the ideal channel | ||
// buffer size should be. | ||
type QueuedChannel[T any] struct { | ||
ch chan T | ||
closeCh chan struct{} | ||
queue *CTQueue[T] | ||
} | ||
|
||
func NewQueuedChannel[T any](channelBufferSize int, capacity int) *QueuedChannel[T] { | ||
queue := &QueuedChannel[T]{ | ||
ch: make(chan T, channelBufferSize), | ||
queue: NewCTQueueWithCapacity[T](capacity), | ||
closeCh: make(chan struct{}), | ||
} | ||
|
||
go func() { | ||
for { | ||
item, ok := queue.queue.Pop() | ||
if !ok { | ||
return | ||
} | ||
|
||
select { | ||
case queue.ch <- item: | ||
|
||
case <-queue.closeCh: | ||
return | ||
} | ||
} | ||
}() | ||
|
||
return queue | ||
} | ||
|
||
func (q *QueuedChannel[T]) Queue(items ...T) bool { | ||
return q.queue.PushMany(items...) | ||
} | ||
|
||
func (q *QueuedChannel[T]) GetChannel() <-chan T { | ||
return q.ch | ||
} | ||
|
||
func (q *QueuedChannel[T]) Close() { | ||
q.queue.Close() | ||
close(q.closeCh) | ||
} |