1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00
ruby--ruby/thread_sync.rb
Jean Boussier 60defe0a68 thread_sync.c: Clarify and document the behavior of timeout == 0
[Feature #18982]

Instead of introducing an `exception: false` argument to have `non_block`
return nil rather than raise, we can clearly document that a timeout of 0
immediately returns.

The code is refactored a bit to avoid doing a time calculation in
such case.
2022-10-17 16:56:00 +02:00

68 lines
2.3 KiB
Ruby

class Thread
class Queue
# call-seq:
# pop(non_block=false, timeout: nil)
#
# Retrieves data from the queue.
#
# If the queue is empty, the calling thread is suspended until data is pushed
# onto the queue. If +non_block+ is true, the thread isn't suspended, and
# +ThreadError+ is raised.
#
# If +timeout+ seconds have passed and no data is available +nil+ is
# returned. If +timeout+ is +0+ it returns immediately.
def pop(non_block = false, timeout: nil)
if non_block && timeout
raise ArgumentError, "can't set a timeout if non_block is enabled"
end
Primitive.rb_queue_pop(non_block, timeout)
end
alias_method :deq, :pop
alias_method :shift, :pop
end
class SizedQueue
# call-seq:
# pop(non_block=false, timeout: nil)
#
# Retrieves data from the queue.
#
# If the queue is empty, the calling thread is suspended until data is
# pushed onto the queue. If +non_block+ is true, the thread isn't
# suspended, and +ThreadError+ is raised.
#
# If +timeout+ seconds have passed and no data is available +nil+ is
# returned. If +timeout+ is +0+ it returns immediately.
def pop(non_block = false, timeout: nil)
if non_block && timeout
raise ArgumentError, "can't set a timeout if non_block is enabled"
end
Primitive.rb_szqueue_pop(non_block, timeout)
end
alias_method :deq, :pop
alias_method :shift, :pop
# call-seq:
# push(object, non_block=false, timeout: nil)
# enq(object, non_block=false, timeout: nil)
# <<(object)
#
# Pushes +object+ to the queue.
#
# If there is no space left in the queue, waits until space becomes
# available, unless +non_block+ is true. If +non_block+ is true, the
# thread isn't suspended, and +ThreadError+ is raised.
#
# If +timeout+ seconds have passed and no space is available +nil+ is
# returned. If +timeout+ is +0+ it returns immediately.
# Otherwise it returns +self+.
def push(object, non_block = false, timeout: nil)
if non_block && timeout
raise ArgumentError, "can't set a timeout if non_block is enabled"
end
Primitive.rb_szqueue_push(object, non_block, timeout)
end
alias_method :enq, :push
alias_method :<<, :push
end
end