class

Termisu::Event::Poller

Inherits Reference / Object

Abstract base class for I/O event multiplexing.

Provides unified interface for system-level event polling with support for file descriptor monitoring and high-precision timers.

Platform Backends

  • Linux: epoll + timerfd for kernel-level timer precision
  • macOS/BSD: kqueue with EVFILT_TIMER
  • Fallback: POSIX poll with monotonic clock timers

Usage

poller = Termisu::Event::Poller.create

# Register file descriptor for read events
poller.register_fd(stdin_fd, FDEvents::Read)

# Add a 16ms repeating timer (~60 FPS)
timer = poller.add_timer(16.milliseconds)

# Event loop
loop do
  case result = poller.wait
  when nil
    break # Shutdown
  else
    case result.type
    when .timer?
      handle_tick(result.timer_expirations)
    when .fd_readable?
      handle_input(result.fd)
    end
  end
end

poller.close

Thread Safety

Poller instances are NOT thread-safe. Use one poller per fiber/thread. File descriptor operations and timer management should occur on the same fiber that calls wait.

Constructors

create

Creates the optimal poller for the current platform.

Returns:

  • Poller::Linux on Linux (epoll + timerfd)
  • Poller::Kqueue on macOS/FreeBSD/OpenBSD
  • Poller::Poll as fallback
Source

Instance methods

add_timer(interval : Time::Span, repeating : Bool = true) : TimerHandle

Creates a new timer with the specified interval.

  • interval - Time between timer expirations
  • repeating - If true, timer auto-rearms; if false, fires once

Returns a TimerHandle for later modification or removal. Raises IO::Error on system error.

Source
close

Releases all resources held by the poller.

Closes internal file descriptors and clears timer state. Safe to call multiple times (idempotent).

Source
modify_timer(handle : TimerHandle, interval : Time::Span) : Nil

Modifies an existing timer's interval.

  • handle - Timer to modify
  • interval - New interval

Raises ArgumentError if handle is invalid.

Source
register_fd(fd : Int32, events : FDEvents) : Nil

Registers a file descriptor for event monitoring.

  • fd - File descriptor to monitor
  • events - Event types to monitor (read, write, error)

Raises IO::Error on system error.

Source
remove_timer(handle : TimerHandle) : Nil

Removes a timer.

Safe to call with already-removed handle (no-op).

Source
unregister_fd(fd : Int32) : Nil

Unregisters a file descriptor from event monitoring.

Safe to call with unregistered fd (no-op).

Source
wait(timeout : Time::Span) : PollResult | Nil

Waits for an event with timeout.

Returns nil if timeout expires without an event. Handles EINTR internally by retrying.

Source
wait

Waits indefinitely for an event.

Blocks until an event occurs. Returns nil if the poller is closed or interrupted in a way that signals shutdown.

Handles EINTR internally by retrying.

Source

Nested types