summaryrefslogtreecommitdiff
path: root/thread_sync.rb
diff options
context:
space:
mode:
authorJean Boussier <jean.boussier@gmail.com>2022-07-26 17:40:00 +0200
committerJean Boussier <jean.boussier@gmail.com>2022-08-02 11:04:28 +0200
commite3aabe93aae87a60ba7b8f1a0fd590534647e352 (patch)
tree3f5c15b61c9914c7e1a34ad56d042dcf70024f75 /thread_sync.rb
parentec3f59309e3f08339c4c76a6881901580801d6cd (diff)
downloadruby-e3aabe93aae87a60ba7b8f1a0fd590534647e352.tar.gz
Implement Queue#pop(timeout: sec)
[Feature #18774] As well as `SizedQueue#pop(timeout: sec)` If both `non_block=true` and `timeout:` are supplied, ArgumentError is raised.
Diffstat (limited to 'thread_sync.rb')
-rw-r--r--thread_sync.rb45
1 files changed, 45 insertions, 0 deletions
diff --git a/thread_sync.rb b/thread_sync.rb
new file mode 100644
index 0000000000..d567ca51af
--- /dev/null
+++ b/thread_sync.rb
@@ -0,0 +1,45 @@
+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.
+ 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.
+ 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
+ end
+end