Class: Queue
- Inherits:
-
Object
- Object
- Queue
- Defined in:
- thread.c,
thread.c
Overview
This class provides a way to synchronize communication between threads.
Example:
require ‘thread’
queue = Queue.new
producer = Thread.new do
5.times do |i|
sleep rand(i) # simulate expense
queue << i
puts "#{i} produced"
end
end
consumer = Thread.new do
5.times do |i|
value = queue.pop
sleep rand(i/2) # simulate expense
puts "consumed #{value}"
end
end
Instance Method Summary collapse
-
#clear ⇒ Object
Removes all objects from the queue.
-
#empty? ⇒ Boolean
Returns
true
if the queue is empty. -
#initialize ⇒ Object
constructor
Creates a new queue instance.
-
#length ⇒ Object
(also: #size)
Returns the length of the queue.
-
#num_waiting ⇒ Object
Returns the number of threads waiting on the queue.
-
#pop(*args) ⇒ Object
(also: #deq, #shift)
Retrieves data from the queue.
-
#push(obj) ⇒ Object
(also: #enq, #<<)
Pushes the given
object
to the queue.
Constructor Details
#initialize ⇒ Object
Creates a new queue instance.
201 202 203 204 205 206 207 |
# File 'thread.c', line 201 static VALUE rb_queue_initialize(VALUE self) { RSTRUCT_SET(self, QUEUE_QUE, ary_buf_new()); RSTRUCT_SET(self, QUEUE_WAITERS, ary_buf_new()); return self; } |
Instance Method Details
#clear ⇒ Object
Removes all objects from the queue.
338 339 340 341 342 343 |
# File 'thread.c', line 338 static VALUE rb_queue_clear(VALUE self) { rb_ary_clear(GET_QUEUE_QUE(self)); return self; } |
#empty? ⇒ Boolean
Returns true
if the queue is empty.
326 327 328 329 330 |
# File 'thread.c', line 326 static VALUE rb_queue_empty_p(VALUE self) { return queue_length(self) == 0 ? Qtrue : Qfalse; } |
#length ⇒ Object #size ⇒ Object Also known as: size
Returns the length of the queue.
354 355 356 357 358 359 |
# File 'thread.c', line 354 static VALUE rb_queue_length(VALUE self) { unsigned long len = queue_length(self); return ULONG2NUM(len); } |
#num_waiting ⇒ Object
Returns the number of threads waiting on the queue.
367 368 369 370 371 372 |
# File 'thread.c', line 367 static VALUE rb_queue_num_waiting(VALUE self) { unsigned long len = queue_num_waiting(self); return ULONG2NUM(len); } |
#pop(non_block = false) ⇒ Object #deq(non_block = false) ⇒ Object #shift(non_block = false) ⇒ Object Also known as: deq, shift
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 an exception is raised.
312 313 314 315 316 317 |
# File 'thread.c', line 312 static VALUE rb_queue_pop(int argc, VALUE *argv, VALUE self) { VALUE should_block = queue_pop_should_block(argc, argv); return queue_do_pop(self, should_block); } |
#push(object) ⇒ Object #enq(object) ⇒ Object #<<(object) ⇒ Object Also known as: enq, <<
Pushes the given object
to the queue.
227 228 229 230 231 |
# File 'thread.c', line 227 static VALUE rb_queue_push(VALUE self, VALUE obj) { return queue_do_push(self, obj); } |