class Makitzo::MultiplexedReader

relays IO from a single source to multiple threads each thread will see the same input. necessarily has to store all data as set of reader threads is not known. possible solution: associate reader with ThreadGroup so we can access list of threads. can then keep track of threads that have read least/most data and discard anything that's no longer needed.

Public Class Methods

new(io) click to toggle source
# File lib/makitzo/multiplexed_reader.rb, line 9
def initialize(io)
  @io, @mutex, @state, @lines = io, Mutex.new, Hash.new { |h,k| h[k] = 0 }, []
end

Public Instance Methods

gets() click to toggle source
# File lib/makitzo/multiplexed_reader.rb, line 13
def gets
  @mutex.synchronize do
    lines_read_by_thread = @state[Thread.current]
    if lines_read_by_thread >= @lines.count
      @lines << @io.gets
    end
    @state[Thread.current] = lines_read_by_thread + 1
    
    line = @lines[lines_read_by_thread]
    line ? line.dup : line
  end
end