Class: LightIO::Core::IOloop

Inherits:
Object
  • Object
show all
Defined in:
lib/lightio/core/ioloop.rb

Overview

IOloop like a per-threaded EventMachine (cause fiber cannot resume cross threads)

IOloop handle io waiting and schedule beams, user do not supposed to directly use this class

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeIOloop

Returns a new instance of IOloop.



8
9
10
11
# File 'lib/lightio/core/ioloop.rb', line 8

def initialize
  @fiber = Fiber.new {run}
  @backend = Backend::NIO.new
end

Class Method Details

.currentObject

return current ioloop or create new one



57
58
59
60
61
62
63
# File 'lib/lightio/core/ioloop.rb', line 57

def current
  key = :"lightio.ioloop"
  unless Thread.current.thread_variable?(key)
    Thread.current.thread_variable_set(key, IOloop.new)
  end
  Thread.current.thread_variable_get(key)
end

Instance Method Details

#add_callback(&blk) ⇒ Object



23
24
25
# File 'lib/lightio/core/ioloop.rb', line 23

def add_callback(&blk)
  @backend.add_callback(&blk)
end

#add_io_wait(io, interests, &blk) ⇒ Object



27
28
29
# File 'lib/lightio/core/ioloop.rb', line 27

def add_io_wait(io, interests, &blk)
  @backend.add_io_wait(io, interests, &blk)
end

#add_timer(timer) ⇒ Object



19
20
21
# File 'lib/lightio/core/ioloop.rb', line 19

def add_timer(timer)
  @backend.add_timer(timer)
end

#cancel_io_wait(io) ⇒ Object



31
32
33
# File 'lib/lightio/core/ioloop.rb', line 31

def cancel_io_wait(io)
  @backend.cancel_io_wait(io)
end

#runObject

should never invoke explicitly



14
15
16
17
# File 'lib/lightio/core/ioloop.rb', line 14

def run
  # start io loop and never return...
  @backend.run
end

#transferObject



51
52
53
# File 'lib/lightio/core/ioloop.rb', line 51

def transfer
  @fiber.transfer
end

#wait(watcher) ⇒ Object

Wait a watcher, watcher can be a timer or socket. see LightIO::Watchers module for detail



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/lightio/core/ioloop.rb', line 37

def wait(watcher)
  future = Future.new
  # add watcher to loop
  id = Object.new
  watcher.set_callback {future.transfer id}
  watcher.start(self)
  # trigger a fiber switch
  # wait until watcher is ok
  # then do work
  if (result = future.value) != id
    raise InvalidTransferError, "expect #{id}, but get #{result}"
  end
end