POE::Loop(3pm)

πŸ’– POE::Loop β€” the manual page, bestie edition πŸ’–

so this is the POE::Loop(3pm) page, from the User Contributed Perl Documentation corner of the universe ✨ it's the whole scoop on POE's event loop bridge interface, and honestly? it's giving infrastructure that carries the entire vibe. let's get into it 🫢


🌸 NAME 🌸

POE::Loop β€” the documentation for POE's event loop bridge interface. that's it, that's the name, no notes πŸ’…


✨ SYNOPSIS ✨

here's the whole interface at a glance, bestie. every one of these gets called as a method on the kernel:

$kernel->loop_initialize();
$kernel->loop_finalize();
$kernel->loop_do_timeslice();
$kernel->loop_run();
$kernel->loop_halt();

$kernel->loop_watch_signal($signal_name);
$kernel->loop_ignore_signal($signal_name);
$kernel->loop_attach_uidestroy($gui_window);

$kernel->loop_resume_time_watcher($next_time);
$kernel->loop_reset_time_watcher($next_time);
$kernel->loop_pause_time_watcher();

$kernel->loop_watch_filehandle($handle, $mode);
$kernel->loop_ignore_filehandle($handle, $mode);
$kernel->loop_pause_filehandle($handle, $mode);
$kernel->loop_resume_filehandle($handle, $mode);

like, that's the whole menu πŸ‘‘ memorize it or don't, we go over all of it below anyway.


πŸ¦‹ DESCRIPTION πŸ¦‹

okay so POE::Loop is a virtual base class that defines a standard event loop interface. it doesn't do the thing itself β€” it's the blueprint. POE::Loop subclasses mix into POE::Kernel and implement the features needed to manage underlying event loops in a consistent fashion. this documentation covers the interface, which is shared by all subclasses. periodt πŸ’…

so here's the lil magic trick: as POE::Kernel loads, it searches through %INC for event loop modules. it loads the most appropriate POE::Loop subclass for the event loop it finds. that subclass slots its methods into POE::Kernel, completing the class at load time. iconic behavior fr fr ✨

and because auto-detection is not always the moment, POE and POE::Kernel provide ways to state the desired event loop in case the auto-detection makes a mistake, or if the developer just prefers to be explicit. if you want the actual how-to, check "Using POE with Other Event Loops" in POE::Kernel β€” that's where you'll find instructions on how to actually use POE with other event loops, the event loop naming conventions, and other details. iykyk 😌

POE::Loop subclasses exist for many of the event loops Perl supports: select(), IO::Poll, WxWindows, EV, Glib, Event, and so on. see CPAN for a full list 🌈


πŸŽ€ GENERAL NOTES πŸŽ€

as previously noted, POE::Loop subclasses provide additional methods to POE::Kernel and are not proper objects in themselves. like, they're not out here living their own object-oriented life. they're helpers πŸ’…

each POE::Loop subclass first defines its own namespace and version within it. this way CPAN and other things can track its version. they then switch to the POE::Kernel package to define their additional methods. sneaky? no. efficient? yes 🫢

POE::Loop is designed as a mix-in class because Perl imposed a performance penalty for method inheritance at the time the class was designed. this could be changed in the future, but it will require cascaded changes in several other classes. so like, don't hold your breath, but also it's not forbidden ⭐

here's a skeleton of a POE::Loop subclass, so you can see the whole shape of it:

use strict;

# YourToolkit bridge for POE::Kernel;

package POE::Loop::YourToolkit;

use vars qw($VERSION);
$VERSION = '1.000'; # NOTE - Should be #.### (three decimal places)

package POE::Kernel;

# Define private lexical data here.
# Implement the POE::Loop interface here.

1;

__END__

=head1 NAME

... documentation goes here ...

=cut

not me showing you the template so you can go make your own bridge πŸ‘‘ literally go off.


🌈 PUBLIC INTERFACE 🌈

POE::Loop's public interface is divided into four parts: administrative methods, signal handler methods, time management methods, and filehandle watcher methods. each group and its members will be described in detail shortly. so like, keep scrolling bestie, we get there πŸ¦‹

POE::Loop subclasses use lexical variables to keep track of things. exact implementation is left up to the subclass' author. for example: POE::Loop::Select keeps its bit vectors for select() calls in class-scoped (static) lexical variables. POE::Loop::Gtk tracks a single time watcher and multiple file watchers there. different vibes, same interface πŸ’…

bridges often employ private methods as callbacks from their event loops. the Event, Gtk, and Tk bridges do this. private callback names should begin with "_loop_" to avoid colliding with other methods. no cap, that underscore prefix is load-bearing 🫢

developers should look at existing bridges to get a feel for things. the "-m" flag for perldoc will show a module in its entirety:

perldoc -m POE::Loop::Select
perldoc -m POE::Loop::Gtk
...

go read the source, it's honestly iconic πŸ”₯


πŸ‘‘ Administrative Methods πŸ‘‘

these methods initialize and finalize an event loop, run the loop to process events, and halt it. the full lifecycle, basically ✨


πŸ’– loop_initialize πŸ’–

initialize the event loop. graphical toolkits especially need some sort of init() call or sequence to set up. for example, Tk requires a widget to be created before any events will be processed, and the program's user interface will be considered destroyed if that widget is closed. so like, this is not optional for Tk, bestie 😭

sub loop_initialize {
  my $self = shift;

  $poe_main_window = Tk::MainWindow->new();
  die "could not create a main Tk window" unless defined $poe_main_window;
  $self->signal_ui_destroy($poe_main_window);
}

and POE::Loop::Select initializes its select() bit vectors here too:

sub loop_initialize {
  @loop_vectors = ( '', '', '' );
  vec($loop_vectors[MODE_RD], 0, 1) = 0;
  vec($loop_vectors[MODE_WR], 0, 1) = 0;
  vec($loop_vectors[MODE_EX], 0, 1) = 0;
}

see? one does GUI stuff, one does bit-vector stuff, same method name 🌸


πŸ’œ loop_finalize πŸ’œ

finalize the event loop. most event loops do not require anything here since they have already stopped by the time loop_finalize() is called. but! this is a good place to check that a bridge has not leaked memory or data. lowkey a vibe check for your bridge 🫢

this example comes from POE::Loop::Event:

sub loop_finalize {
  my $self = shift;

  foreach my $fd (0..$#fileno_watcher) {
    next unless defined $fileno_watcher[$fd];
    foreach my $mode (MODE_RD, MODE_WR, MODE_EX) {
      POE::Kernel::_warn(
        "Mode $mode watcher for fileno $fd is defined during loop finalize"
      ) if defined $fileno_watcher[$fd]->[$mode];
    }
  }

  $self->loop_ignore_all_signals();
}

see, it's out here catching leftover watchers and yelling about it, and then ignoring all the signals. cleanup queen πŸ‘‘


πŸ¦‹ loop_do_timeslice πŸ¦‹

wait for time to pass or new events to occur, and dispatch any events that become due. that's the whole job description ✨

if the underlying event loop does this through callbacks, then loop_do_timeslice() will either provide minimal glue or do nothing at all. it's giving "depends on your bridge" energy.

for example, loop_do_timeslice() for POE::Loop::Select sets up and calls select(). if any files or other resources become active, it enqueues events for them. finally, it triggers dispatch for any events are due.

on the other hand, the Gtk event loop handles all this, so loop_do_timeslice() is empty for the Gtk bridge. literally nothing in the function body. slay πŸ’…

a sample loop_do_timeslice() implementation is not presented here because it would either be quite large or empty. see each POE::Loop::IO_Poll or Select for large ones. Event and Gtk are empty.

the bridges for Poll and Select for large ones. the ones for Event and Gtk are empty, and Tk's (in POE::Loop::TkCommon) is rather small. so like, size varies wildly, that's just the truth 🌈


⭐ loop_run ⭐

run an event loop until POE has no more sessions to handle events. this method tends to be quite small, and it is often implemented in terms of loop_do_timeslice(). for example, POE::Loop::IO_Poll implements it:

sub loop_run {
  my $self = shift;
  while ($self->_data_ses_count()) {
    $self->loop_do_timeslice();
  }
}

this method is even more trivial when an event loop handles it. this is from the Gtk bridge:

sub loop_run {
  unless (defined $_watcher_timer) {
    $_watcher_timer = Gtk->idle_add(\&_loop_resume_timer);
  }
  Gtk->main;
}

two lines and a dream, bestie πŸŽ€


πŸ’€ loop_halt πŸ’€

loop_halt() does what it says: it halts POE's underlying event loop. it tends to be either trivial for external event loops or empty for ones that are implemented in the bridge itself (IO_Poll, Select). no drama, no ceremony.

for example, the loop_run() method in the Poll bridge exits when sessions have run out, so its loop_halt() method is empty:

sub loop_halt {
  # does nothing
}

Gtk, however, needs to be stopped because it does not know when POE is done:

sub loop_halt {
  Gtk->main_quit();
}

like, Gtk doesn't read minds, you have to tell it 😭


🌸 Signal Management Methods 🌸

these methods enable and disable signal watchers. they are used by POE::Resource::Signals to manage an event loop's signal watchers. that's the whole point of them, no hidden agenda πŸ’…

most event loops use Perl's %SIG to watch for signals. this is so common that POE::Loop::PerlSignals implements the interface on behalf of other subclasses. one class, doing the work for everyone, we love a shared resource 🫢


πŸ’– loop_watch_signal SIGNAL_NAME πŸ’–

watch for a given SIGNAL_NAME. SIGNAL_NAME is the version found in %SIG, which tends to be the operating signal's name with the leading "SIG" removed. so like, INT, not SIGINT. iykyk ✨

POE::Loop::PerlSignals' implementation adds callbacks to %SIG except for CHLD/CLD, which begins a waitpid() polling loop instead. different treatment for a different job.

as of this writing, all of the POE::Loop subclasses register their signal handlers through POE::Loop::PerlSignals. no cap, all of them.

there are three types of signal handlers:

  • CHLD/CLD handlers β€” when managed by the bridges themselves, these poll for exited children. POE::Kernel does most of this, but loop_watch_signal() still needs to start the process.
  • PIPE handlers β€” the PIPE signal event must be sent to the session that is active when the signal occurred. very specific, very important.
  • Everything else β€” signal events for everything else are sent to POE::Kernel, where they are distributed to every session.

the loop_watch_signal() methods tends to be very long, so an example is not presented here. the Event and Select bridges have good examples, though. go look at those if you want the full drama πŸ”₯


🧚 loop_ignore_signal SIGNAL_NAME 🧚

stop watching SIGNAL_NAME. POE::Loop::PerlSignals does this by resetting the %SIG for the SIGNAL_NAME to a sane value. put it back how you found it, basically πŸ’…

$SIG{CHLD} is left alone so as to avoid interfering with system() and other things. hands off, do not touch 🫢

SIGPIPE is generally harmless since POE generates events for this condition. therefore $SIG{PIPE} is set to "IGNORE" when it's not being handled.

all other signal handlers default to "DEFAULT" when not in use. clean, predictable, iconic ⭐


πŸŽ€ loop_attach_uidestroy WIDGET πŸŽ€

POE, when used with a graphical toolkit, should shut down when the user interface is closed. loop_attach_uidestroy() is used to shut down POE when a particular WIDGET is destroyed.

the shutdown is done by firing a UIDESTROY signal when the WIDGET's closure or destruction callback is invoked. UIDESTROY guarantees the program will shut down by virtue of being terminal and non-maskable. like, it will happen. it cannot be stopped 😀

loop_attach_uidestroy() is only meaningful in POE::Loop subclasses that tie into user interfaces. all other subclasses leave the method empty.

here's Gtk's:

sub loop_attach_uidestroy {
  my ($self, $window) = @_;
  $window->signal_connect(
    delete_event => sub {
      if ($self->_data_ses_count()) {
        $self->_dispatch_event(
          $self, $self,
          EN_SIGNAL, ET_SIGNAL, [ 'UIDESTROY' ],
          __FILE__, __LINE__, undef, monotime(), -__LINE__
        );
      }
      return 0;
    }
  );
}

that's a whole callback inside a callback and it's lowkey gorgeous 🌈


πŸ’œ Alarm and Time Management Methods πŸ’œ

these methods enable and disable a time watcher or alarm in the underlying event loop. POE only requires one, which is reused or re-created as necessary. one watcher, maximum efficiency, that's the energy πŸ’…


okay that's the first half, bestie β€” the time watcher methods themselves and the filehandle watcher methods are still coming, so don't go anywhere 🫢✨

Most event loops are literally just "okay bestie, time passed, here's a callback πŸ’…". So it's the bridge's whole job to register and unregister that callback whenever it's needed. When it gets invoked, the callback should dispatch all the events that have become due, and possibly set up a new callback for the next event that needs dispatching. That's it. That's the assignment. ✨

The time management methods may accept NEXT_EVENT_TIME. That's the time the next event will become due, measured in UNIX epoch time. NEXT_EVENT_TIME is a real number and it can have sub-second accuracy (yes, she's precise like that πŸ’…). It is the bridge's responsibility to convert that value into whatever the underlying event loop actually wants.

loop_resume_time_watcher NEXT_EVENT_TIME

Resume an already active time watcher 🫢. It gets used together with loop_pause_time_watcher() to give you a less expensive way of toggling timers for those frequent-use cases. And like we said above: NEXT_EVENT_TIME is in UNIX epoch time and may have sub-second accuracy.

loop_resume_time_watcher() is what bridges use when they set their watchers in the underlying event loop. For example, POE::Loop::Gtk implements it like this:

sub loop_resume_time_watcher {
  my ($self, $next_time) = @_;
  $next_time -= time();
  $next_time *= 1000;
  $next_time = 0 if $next_time < 0;
  $_watcher_timer = Gtk->timeout_add(
    $next_time, \&_loop_event_callback
  );
}

For bridges that implement their own event loops, this method is usually empty. Not a single thing to do. Living that empty-sub life. πŸ’€

loop_reset_time_watcher NEXT_EVENT_TIME

Reset a time watcher, often by stopping or destroying an existing one and creating a brand new one in its place πŸ”₯. It's often a wrapper for loop_resume_time_watcher() that first destroys an existing watcher. Like, for example, POE::Loop::Gkt's implementation:

sub loop_reset_time_watcher {
  my ($self, $next_time) = @_;
  Gtk->timeout_remove($_watcher_timer);
  undef $_watcher_timer;
  $self->loop_resume_time_watcher($next_time);
}

loop_pause_time_watcher

Pause a time watcher without destroying it β€” but only if the underlying event loop actually supports such a thing. POE::Loop::Event does support it:

sub loop_pause_time_watcher {
  $_watcher_timer or return;
  $_watcher_timer->stop();
}

File Activity Management Methods πŸŽ€

These methods turn file activity watchers on and off. There are four of them: loop_watch_filehandle(), loop_ignore_filehandle(), loop_pause_filehandle(), and loop_resume_filehandle(). The "pause" and "resume" ones are the lightweight versions of "ignore" and "watch", respectively. Same energy, way less overhead. 🌸

All of these methods take the same two parameters: a file HANDLE and a file access MODE. Modes may be MODE_RD, MODE_WR, or MODE_EX. These constants are defined by POE::Kernel and they correspond to the semantics of POE::Kernel's select_read(), select_write(), and select_expedite() methods. iykyk πŸ’œ

POE calls MODE_EX "expedited" because it often signals that a file is ready for out-of-band information. Not every event loop handles MODE_EX, though. Take Tk, for example:

sub loop_watch_filehandle {
  my ($self, $handle, $mode) = @_;
  my $fileno = fileno($handle);

  my $tk_mode;
  if ($mode == MODE_RD) {
    $tk_mode = 'readable';
  }
  elsif ($mode == MODE_WR) {
    $tk_mode = 'writable';
  }
  else {
    # The Tk documentation implies by omission that expedited
    # filehandles aren't, uh, handled.  This is part 1 of 2.
    confess "Tk does not support expedited filehandles";
  }

  # ... rest omitted ....
}

loop_watch_filehandle FILE_HANDLE, IO_MODE

Watch a FILE_HANDLE for activity in a given IO_MODE πŸ‘€. Depending on the underlying event loop, a watcher or callback will get registered for the FILE_HANDLE. Activity in the specified IO_MODE (read, write, or out of band) will trigger emission of the proper event in application space.

POE::Loop::Select sets the fileno()'s bit in the proper select() bit vector. It also keeps track of which file descriptors are active:

sub loop_watch_filehandle {
  my ($self, $handle, $mode) = @_;
  my $fileno = fileno($handle);
  vec($loop_vectors[$mode], $fileno, 1) = 1;
  $loop_filenos{$fileno} |= (1<<$mode);
}

loop_ignore_filehandle FILE_HANDLE, IO_MODE

Stop watching the FILE_HANDLE in a given IO_MODE βœ‹. This stops (and possibly destroys) an event watcher that corresponds to the FILE_HANDLE and IO_MODE.

POE::Loop::IO_Poll's loop_ignore_filehandle() manages descriptor/mode bits for its _poll() method right here. It also does some cleanup if a descriptor is no longer being watched after this ignore call:

sub loop_ignore_filehandle {
  my ($self, $handle, $mode) = @_;
  my $fileno = fileno($handle);

  my $type = mode_to_poll($mode);
  my $current = $poll_fd_masks{$fileno} || 0;
  my $new = $current & ~$type;

  if (TRACE_FILES) {
    POE::Kernel::_warn(
      sprintf(
        "<fh> Ignore $fileno: " .
        ": Current mask: 0x%02X - removing 0x%02X = 0x%02X\n",
        $current, $type, $new
      )
    );
  }

  if ($new) {
    $poll_fd_masks{$fileno} = $new;
  }
  else {
    delete $poll_fd_masks{$fileno};
  }
}

loop_pause_filehandle FILE_HANDLE, IO_MODE

This one is a lightweight form of loop_ignore_filehandle() πŸ¦‹. It's used alongside loop_resume_filehandle() to temporarily toggle a watcher's state for a FILE_HANDLE in a particular IO_MODE.

Some event loops, like Event.pm, support their file watchers being disabled and re-enabled without needing to destroy and re-create the watcher objects:

sub loop_pause_filehandle {
  my ($self, $handle, $mode) = @_;
  my $fileno = fileno($handle);
  $fileno_watcher[$fileno]->[$mode]->stop();
}

By comparison, Event's loop_ignore_filehandle() method cancels and destroys the watcher object:

sub loop_ignore_filehandle {
  my ($self, $handle, $mode) = @_;
  my $fileno = fileno($handle);
  if (defined $fileno_watcher[$fileno]->[$mode]) {
    $fileno_watcher[$fileno]->[$mode]->cancel();
    undef $fileno_watcher[$fileno]->[$mode];
  }
}

Ignoring and re-creating watchers is relatively expensive, so POE::Kernel's select_pause_read() and select_resume_read() methods (and the corresponding ones for write and expedite) use the faster versions instead. Efficiency queen πŸ‘‘

loop_resume_filehandle FILE_HANDLE, IO_MODE

This is a lightweight form of loop_watch_filehandle() ✨. It's used along with loop_pause_filehandle() to temporarily toggle a watcher's state for a FILE_HANDLE in a particular IO_MODE.


HOW POE FINDS EVENT LOOP BRIDGES πŸ”

This is a rehash of "Using POE with Other Event Loops" in POE::Kernel.

First things first: if a POE::Loop subclass is manually loaded before POE::Kernel, then that one gets used. End of story. Periodt. πŸ’…

If one isn't, POE::Kernel goes searching for an external event loop module in %INC. For each module in %INC, it tries the corresponding POE::XS::Loop and POE::Loop subclasses.

So, for example, if IO::Poll is loaded, POE::Kernel tries:

use POE::XS::Loop::IO_Poll;
use POE::Loop::IO_Poll;

This is relatively expensive, ngl 😭, but it makes sure POE::Kernel can find new POE::Loop subclasses without anyone having to define them in some central registry. No gatekeeping here.

POE::Loop::Select is the fallback event loop. It gets loaded if no other event loop can be found in %INC. She's the reliable bestie who shows up when everyone else flakes 🫢.

It can't be repeated often enough: event loops must be loaded before POE::Kernel. Otherwise they will not be present in %INC, and POE::Kernel will not detect them. Not a vibe. Do not do this. πŸ™ˆ

SEE ALSO 🌈

POE, POE::Loop::Event, POE::Loop::Gtk, POE::Loop::IO_Poll, POE::Loop::Select, POE::Loop::Tk.

POE::Test::Loops is POE's event loop tests, released as a separate, reusable distribution. POE::Loop authors are encouraged to use the tests for their own distributions β€” go off, test your loops, you got this πŸ’ͺ


BUGS πŸ’€

None known. Not a single one. She's flawless, apparently. We love a bug-free era. ✨


AUTHORS & LICENSING πŸ‘‘

Please see POE for more information about authors, contributors, and POE's licensing. The receipts are all over there, bestie. πŸŽ€


And that's the whole page, fr fr! This one came from perl v5.34.0, dated 2022-03-25, and it's POE::Loop(3pm) β€” go forth and bridge those event loops, you absolute icon πŸ’–πŸ¦‹πŸŒΈ

πŸ“¦ where this page comes from