Class: Reactomatic::Reactor

Inherits:
Object
  • Object
show all
Defined in:
lib/reactomatic/reactor.rb

Constant Summary collapse

SELECTOR_TIMEOUT =

Seconds.

0.1

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Reactor

Returns a new instance of Reactor.



5
6
7
8
9
10
# File 'lib/reactomatic/reactor.rb', line 5

def initialize(opts = {})
  @selector = NIO::Selector.new
  @selector_timeout = opts[:selector_timeout] || SELECTOR_TIMEOUT
  @run_lock = Mutex.new
  @next_tick_queue = Queue.new
end

Instance Method Details

#deregister(io) ⇒ Object



42
43
44
45
46
# File 'lib/reactomatic/reactor.rb', line 42

def deregister(io)
  @selector.deregister(io)

  nil
end

#next_tick(callback = nil, &block) ⇒ Object



52
53
54
55
56
57
58
# File 'lib/reactomatic/reactor.rb', line 52

def next_tick(callback = nil, &block)
  func = callback || block

  @next_tick_queue.push(func)

  nil
end

#register(io, interest, target) ⇒ Object



35
36
37
38
39
40
# File 'lib/reactomatic/reactor.rb', line 35

def register(io, interest, target)
  monitor = @selector.register(io, interest)
  monitor.value = target

  nil
end

#registered?(io) ⇒ Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/reactomatic/reactor.rb', line 48

def registered?(io)
  @selector.registered?(io)
end

#schedule(callback = nil, &block) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
# File 'lib/reactomatic/reactor.rb', line 60

def schedule(callback = nil, &block)
  func = callback || block

  if Thread.current == @thread
    func.call
  else
    next_tick(func)
  end

  nil
end

#start(opts = {}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/reactomatic/reactor.rb', line 12

def start(opts = {})
  @run_lock.synchronize do
    raise AlreadyStarted if @thread
    @thread = Thread.new do
      begin
        while !@selector.closed?
          process_next_tick_queue
          monitor_io_objects
        end
      rescue Exception => e
        exception_handler(e)
      end
    end
  end
end

#stopObject



28
29
30
31
32
33
# File 'lib/reactomatic/reactor.rb', line 28

def stop
  @run_lock.synchronize do
    @selector.close
    @thread.join
  end
end