Class: RubyChannel::Selector

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_channel/selector.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeSelector

Returns a new instance of Selector.



6
7
8
9
10
11
# File 'lib/ruby_channel/selector.rb', line 6

def initialize
  @threads       = []
  @waiting       = true
  @mutex         = Mutex.new
  @return_thread = nil
end

Instance Attribute Details

#mutexObject (readonly)

Returns the value of attribute mutex.



3
4
5
# File 'lib/ruby_channel/selector.rb', line 3

def mutex
  @mutex
end

#resultObject (readonly)

Returns the value of attribute result.



3
4
5
# File 'lib/ruby_channel/selector.rb', line 3

def result
  @result
end

#waitingObject (readonly) Also known as: waiting?

Returns the value of attribute waiting.



3
4
5
# File 'lib/ruby_channel/selector.rb', line 3

def waiting
  @waiting
end

Instance Method Details

#default(&block) ⇒ Object



31
32
33
34
35
36
37
38
# File 'lib/ruby_channel/selector.rb', line 31

def default(&block)
  default_channel = Channel.new
  Thread.new do
    Thread.current[:name]  = "Default Listener" if RubyChannel::CHANNEL_DEBUG
    default_channel << :default
  end
  listen default_channel, &block
end

#listen(channel, &block) ⇒ Object



13
14
15
16
17
18
19
# File 'lib/ruby_channel/selector.rb', line 13

def listen(channel, &block)
  selector = self
  @threads << Thread.new do
    Thread.current[:name]  = "Listener" if RubyChannel::CHANNEL_DEBUG
    channel.subscribe(selector, &block)
  end
end

#release_resultObject



59
60
61
# File 'lib/ruby_channel/selector.rb', line 59

def release_result
  @return_thread.run if @return_thread
end

#selectObject



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/ruby_channel/selector.rb', line 40

def select
  Thread.current[:name] = "select" if RubyChannel::CHANNEL_DEBUG
  @mutex.synchronize do
    if waiting?
      @return_thread = Thread.current
      Thread.list.each{|t| puts "#{t.inspect}: #{t[:name]}"} if RubyChannel::CHANNEL_DEBUG
      @mutex.sleep
    end
  end
  @threads.each{ |thread| thread.wakeup if thread.alive? }
  @threads.clear
  return @result
end

#timeout(value, &block) ⇒ Object



21
22
23
24
25
26
27
28
29
# File 'lib/ruby_channel/selector.rb', line 21

def timeout(value, &block)
  timeout_channel = Channel.new
  Thread.new do
    Thread.current[:name]  = "Timeout Listener" if RubyChannel::CHANNEL_DEBUG
    sleep value
    timeout_channel << :timeout
  end
  listen timeout_channel, &block
end

#update_result(channel, value) ⇒ Object



54
55
56
57
# File 'lib/ruby_channel/selector.rb', line 54

def update_result(channel, value)
  @waiting = false
  @result  = value
end