| Class | SizedQueue |
| In: |
lib/thread.rb
|
| Parent: | Queue |
This class represents queues of specified size capacity. The push operation may be blocked if the capacity is full.
See Queue for an example of how a SizedQueue works.
Creates a fixed-length queue with a maximum size of max.
# File lib/thread.rb, line 379
379: def initialize(max)
380: raise ArgumentError, "queue size must be positive" unless max > 0
381: @max = max
382: @queue_wait = []
383: @queue_wait.taint # enable tainted comunication
384: super()
385: end
Returns the maximum size of the queue.
# File lib/thread.rb, line 390
390: def max
391: @max
392: end
Sets the maximum size of the queue.
# File lib/thread.rb, line 397
397: def max=(max)
398: Thread.critical = true
399: if max <= @max
400: @max = max
401: Thread.critical = false
402: else
403: diff = max - @max
404: @max = max
405: Thread.critical = false
406: diff.times do
407: begin
408: t = @queue_wait.shift
409: t.run if t
410: rescue ThreadError
411: retry
412: end
413: end
414: end
415: max
416: end
Returns the number of threads waiting on the queue.
# File lib/thread.rb, line 478
478: def num_waiting
479: @waiting.size + @queue_wait.size
480: end
Retrieves data from the queue and runs a waiting thread, if any.
# File lib/thread.rb, line 445
445: def pop(*args)
446: retval = super
447: Thread.critical = true
448: if @que.length < @max
449: begin
450: t = @queue_wait.shift
451: t.wakeup if t
452: rescue ThreadError
453: retry
454: ensure
455: Thread.critical = false
456: end
457: begin
458: t.run if t
459: rescue ThreadError
460: end
461: end
462: retval
463: end
Pushes obj to the queue. If there is no space left in the queue, waits until space becomes available.
# File lib/thread.rb, line 422
422: def push(obj)
423: Thread.critical = true
424: while @que.length >= @max
425: @queue_wait.push Thread.current
426: Thread.stop
427: Thread.critical = true
428: end
429: super
430: end