Bug #22719
openMutex, Queue and SizedQueue lose the wakeup when the woken waiter is interrupted
Description
Mutex#unlock, Queue#push and SizedQueue#pop wake exactly one waiter. If that waiter then leaves without taking the resource, it does not pass the wakeup on, and the next waiter sleeps next to a free mutex, a queued item or a free slot until some other thread happens to use the primitive again. For Mutex, if no other thread does, the program hangs and the deadlock detector does not report it (thread.c treats "unlocked with waiters" as live).
# Mutex (also Monitor#synchronize, MonitorMixin)
m = Mutex.new; m.lock
a = Thread.new { m.synchronize {} rescue nil }; Thread.pass until a.stop?
b = Thread.new { m.synchronize {} }; Thread.pass until b.stop?
m.unlock # wakes a
a.raise("x") # Thread#raise / Thread#kill / Timeout / a raising trap handler
a.join
p b.join(2), m.locked? #=> nil, false (expected: b finishes)
# Queue#pop: same shape with q.push(:item); a.raise -> q.size == 1, b still in pop
# SizedQueue#push: same shape with q.pop; a.raise -> free slot, b still in push
# SizedQueue#push(timeout:): no interrupt needed; a pull request for that case follows
- Mutex/Monitor:
do_mutex_lockreleases ownership beforeRUBY_VM_CHECK_INTS_BLOCKING(thread_sync.c:366-376 on master), which c1d78a7f0e added for [Bug #15360] / [Bug #15645]; when the check raises, no other waiter is woken. Since 2.5.9 / 2.6. - Queue#pop and SizedQueue#push on interrupt:
queue_sleep_done/szqueue_sleep_done(thread_sync.c:999-1018) only unlink the waiter. Seen on every version tested, 2.1 to master. - SizedQueue#push(timeout:): the pusher chosen by
popreturns nil at thread_sync.c:1134-1135 once its deadline has passed, even with the slot free. Since 3.2 (Feature #18944). A separate small pull request fixes this case.
A possible direction for the interrupt cases: on those exit paths, when the waiter had been chosen and the resource is still available, wake the next waiter (for Mutex, the same walk rb_mutex_unlock_th does). Doing it only on the exceptional path avoids extra spurious wakeups on the normal path, but needs to know whether the interrupt check is raising; which trade-off is acceptable is a design decision, so I have not prepared a patch for those.
Reproduced deterministically on 3.4.13, 4.0.10 and master.
Updated by saddestmartian (sad mart) 1 day ago
A pull request for the SizedQueue#push(timeout:) case: https://github.com/ruby/ruby/pull/20478