Class: Queue

Inherits:
Object
  • Object
show all
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

Constructor Details

#initializeObject

Creates a new queue instance.



211
212
213
214
215
216
217
# File 'thread.c', line 211

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

#clearObject

Removes all objects from the queue.



345
346
347
348
349
350
# File 'thread.c', line 345

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.

Returns:

  • (Boolean)


333
334
335
336
337
# File 'thread.c', line 333

static VALUE
rb_queue_empty_p(VALUE self)
{
    return queue_length(self) == 0 ? Qtrue : Qfalse;
}

#lengthObject #sizeObject Also known as: size

Returns the length of the queue.



361
362
363
364
365
366
# File 'thread.c', line 361

static VALUE
rb_queue_length(VALUE self)
{
    unsigned long len = queue_length(self);
    return ULONG2NUM(len);
}

#marshal_dumpObject

:nodoc:



563
564
565
566
567
568
# File 'thread.c', line 563

static VALUE
undumpable(VALUE obj)
{
    rb_raise(rb_eTypeError, "can't dump %"PRIsVALUE, rb_obj_class(obj));
    UNREACHABLE;
}

#num_waitingObject

Returns the number of threads waiting on the queue.



374
375
376
377
378
379
# File 'thread.c', line 374

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.



319
320
321
322
323
324
# File 'thread.c', line 319

static VALUE
rb_queue_pop(int argc, VALUE *argv, VALUE self)
{
    int 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.



237
238
239
240
241
# File 'thread.c', line 237

static VALUE
rb_queue_push(VALUE self, VALUE obj)
{
    return queue_do_push(self, obj);
}