Sha256: 1c0b3d0849fef0c00ef18963faafeac4219958a77077fd1b1e4eee95b90be25c

Contents?: true

Size: 962 Bytes

Versions: 17

Compression:

Stored size: 962 Bytes

Contents

require 'thread'

# スレッドを使ったGenerator
class ThreadUseGenerator
  def initialize( enum, buff_size=nil )
    @alive = true
    @alive_mutex = Mutex.new
    @q = buff_size ? SizedQueue.new( buff_size ) : Queue.new

    @end = Object.new
    @t = Thread.fork {
      begin
        enum.each {|*items|
          break unless @alive_mutex.synchronize { @alive }
          @q << items
        }
      ensure
        @q << @end
      end
    }
    Thread.pass

    @has_next = true
    inner_next
  end

  def next?
    @has_next
  end
  def next
    raise "illegal state." unless next?
    begin
      @next_element
    ensure
      inner_next
    end
  end
  def close
    @alive_mutex.synchronize {
      @alive = false
    }
    @has_next = false
    @q.clear
    @t.join
  end
private
  def inner_next
    item = @q.pop
    @has_next = false if @end.equal? item
    @next_element = item
  end
end

Version data entries

17 entries across 17 versions & 2 rubygems

Version Path
unageanu-jiji-0.1.0 lib/jiji/util/thread_use_generator.rb
unageanu-jiji-1.0.0 lib/jiji/util/thread_use_generator.rb
unageanu-jiji-1.0.1 lib/jiji/util/thread_use_generator.rb
unageanu-jiji-1.0.2 lib/jiji/util/thread_use_generator.rb
unageanu-jiji-1.0.3 lib/jiji/util/thread_use_generator.rb
unageanu-jiji-1.1.0 lib/jiji/util/thread_use_generator.rb
unageanu-jiji-1.1.1 lib/jiji/util/thread_use_generator.rb
unageanu-jiji-1.1.2 lib/jiji/util/thread_use_generator.rb
unageanu-jiji-1.1.3 lib/jiji/util/thread_use_generator.rb
unageanu-jiji-1.1.4 lib/jiji/util/thread_use_generator.rb
unageanu-jiji-1.2.1 lib/jiji/util/thread_use_generator.rb
unageanu-jiji-1.2.3 lib/jiji/util/thread_use_generator.rb
unageanu-jiji-1.2.4 lib/jiji/util/thread_use_generator.rb
jiji-1.2.8 lib/jiji/util/thread_use_generator.rb
jiji-1.2.7 lib/jiji/util/thread_use_generator.rb
jiji-1.2.6 lib/jiji/util/thread_use_generator.rb
jiji-1.2.5 lib/jiji/util/thread_use_generator.rb