diff --git a/lib/nps_mux/queue.go b/lib/nps_mux/queue.go index a4bfb14..a194066 100644 --- a/lib/nps_mux/queue.go +++ b/lib/nps_mux/queue.go @@ -275,6 +275,11 @@ startPop: if element != nil { return } + // the element counted in length may have been taken by release() when the + // window was closed concurrently, re-check the length instead of spinning forever + if length, _ = Self.chain.head.unpack(atomic.LoadUint64(&Self.lengthWait)); length == 0 { + goto startPop + } runtime.Gosched() // another goroutine is still pushing } } diff --git a/lib/nps_mux/queue_test.go b/lib/nps_mux/queue_test.go new file mode 100644 index 0000000..8c2fd6f --- /dev/null +++ b/lib/nps_mux/queue_test.go @@ -0,0 +1,33 @@ +package nps_mux + +import ( + "io" + "sync/atomic" + "testing" + "time" +) + +// A reader that has already seen an element counted in length must not spin +// forever when release() takes that element first because the conn was closed. +func TestReceiveWindowQueuePopAfterConcurrentRelease(t *testing.T) { + q := newReceiveWindowQueue() + // the reader sees one element in the queue... + atomic.StoreUint64(&q.lengthWait, q.chain.head.pack(1, 0)) + done := make(chan error, 1) + go func() { + _, err := q.Pop() + done <- err + }() + time.Sleep(10 * time.Millisecond) + // ...but the window is closed and release() drains that element first + q.Stop() + atomic.StoreUint64(&q.lengthWait, 0) + select { + case err := <-done: + if err != io.EOF { + t.Fatalf("Pop returned %v, want io.EOF", err) + } + case <-time.After(time.Second): + t.Fatal("Pop is still spinning after the queue was stopped and drained") + } +}