Skip to content

Commit

Permalink
Merge pull request #11 from Cleverse/feat/queue/try-dequeue
Browse files Browse the repository at this point in the history
Add non-blocking "TryDequeue" function in queue lib
  • Loading branch information
Planxnx authored Nov 6, 2023
2 parents acfadfb + ea3d6ed commit bdb9d3d
Showing 1 changed file with 17 additions and 0 deletions.
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

0 comments on commit bdb9d3d

Please sign in to comment.