Sha256: 971b92dff950d791ffa4e15491b40b905e695837bddb1bba5bde5cb4edec1f5a

Contents?: true

Size: 1.15 KB

Versions: 3

Compression:

Stored size: 1.15 KB

Contents

require 'thwait'

module LightIO::Library
  class ThreadsWait
    ErrNoWaitingThread = ::ThreadsWait::ErrNoWaitingThread
    ErrNoFinishedThread = ::ThreadsWait::ErrNoFinishedThread

    attr_reader :threads

    def initialize(*threads)
      @threads = threads
    end

    def all_waits
      until empty?
        thr = next_wait
        yield thr if block_given?
      end
    end

    def empty?
      @threads.empty?
    end

    def finished?
      @threads.any? {|thr| !thr.alive?}
    end

    def join(*threads)
      join_nowait(*threads)
      next_wait
    end

    def join_nowait(*threads)
      @threads.concat(threads)
    end

    def next_wait(nonblock=nil)
      raise ThreadsWait::ErrNoWaitingThread, 'No threads for waiting.' if empty?
      @threads.each do |thr|
        if thr.alive? && nonblock
          next
        elsif thr.alive?
          thr.join
        end
        # thr should dead
        @threads.delete(thr)
        return thr
      end
      raise ThreadsWait::ErrNoFinishedThread, 'No finished threads.'
    end

    class << self
      def all_waits(*threads, &blk)
        new(*threads).all_waits(&blk)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
lightio-0.3.2 lib/lightio/library/threads_wait.rb
lightio-0.3.1 lib/lightio/library/threads_wait.rb
lightio-0.3.0 lib/lightio/library/threads_wait.rb