Skip to content

Commit 4eb92b5

Browse files
committed
Fix potential issues of LinkedListQueue.
1 parent 92f977c commit 4eb92b5

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

queue.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,12 +340,23 @@ func (q *LinkedListQueue[T]) Poll() (T, error) {
340340
return q.Shift()
341341
}
342342

343+
// Peek Peek the T val from the first position without removing it (non-blocking)
344+
func (q *LinkedListQueue[T]) Peek() (T, error) {
345+
node := q.first
346+
if node == nil {
347+
return *new(T), ErrQueueIsEmpty
348+
}
349+
return *node.Val, nil
350+
}
351+
343352
// Shift Shift the T val from the first position (non-blocking)
344353
func (q *LinkedListQueue[T]) Shift() (T, error) {
345354
node := q.first
346355
if node == nil {
347356
return *new(T), ErrQueueIsEmpty
348357
}
358+
359+
// Remove the first item
349360
q.count--
350361
q.first = node.Next
351362
if q.first == nil {
@@ -369,6 +380,9 @@ func (q *LinkedListQueue[T]) Unshift(val T) error {
369380
node.Val = &val
370381

371382
q.count++
383+
if q.last == nil {
384+
q.last = node
385+
}
372386
first := q.first
373387
q.first = node
374388
node.Next = first

queue_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,4 +237,22 @@ func TestLinkedListQueue(t *testing.T) {
237237
assert.Equal(t, 0, linkedListQueue.Count())
238238
assert.Equal(t, 0, linkedListQueue.nodeCount)
239239
assert.Nil(t, linkedListQueue.nodePoolFirst)
240+
241+
go func() {
242+
time.Sleep(1 * time.Millisecond)
243+
244+
for i := 1; i <= 10000; i++ {
245+
result, err := concurrentQueue.Take()
246+
assert.Equal(t, nil, err)
247+
assert.Equal(t, i, result)
248+
}
249+
}()
250+
go func() {
251+
for i := 1; i <= 10000; i++ {
252+
err := concurrentQueue.Offer(i)
253+
assert.Equal(t, nil, err)
254+
}
255+
}()
256+
257+
time.Sleep(2 * timeout)
240258
}

0 commit comments

Comments
 (0)