Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add non-blocking "TryDequeue" function in queue lib #11

Merged
merged 1 commit into from
Nov 6, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions queue/queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,23 @@ func (q *Queue[T]) Dequeue() (val T, ok bool) {
return item, true
}

// TryDequeue removes an item from the front of the queue, similar to Dequeue.
//
// However, TryDequeue does NOT block if the queue is empty. It returns second value as false immediately if the queue is empty or closed.
func (q *Queue[T]) TryDequeue() (val T, ok bool) {
q.mu.Lock()
defer q.mu.Unlock()

if q.isClosed || len(q.items) == 0 {
return val, false
}

item := q.items[0]
q.items = q.items[1:]

return item, true
}

// IsEmpty returns true if the queue is empty.
func (q *Queue[T]) IsEmpty() bool {
q.mu.RLock()
Expand Down