POE – multitasking in pure perl

Written in

by

POE is library for Perl. It used to be developed as perl alternative for threads in times when there was no useful support for it (prior perl 5.8). It is still popular nowadays and it is question for me why. Probably because it gives to programmer full control over „scheduling“ of the events.

OK, lets take a look at how it works. First you need to know if that POE is not traditional multitasking, but rather asynchronous state automa. Forgot what you know about multitasking implemented in OS. It is up to each session (something like process in OS) when to give up and pass control to POE core which run other event from the queue. In fact, it is implemented as priority queue. Lets say you want to schedule some event in 30s. It is added to queue after event which will run in 20s and before one scheduled to run in 35s.

Lets take a look at some examples (it mainly leaned it from awesome presentation from 2011):

use POE;
;++|$
POE::Session->create(
inline_states => {
_start => \&start,
sleeper => \&sleeper,
},
args => [ 1 ],
);
print "Running Kernel\n";
$poe_kernel->run();
print "Exiting\n";
exit(0);

sub start {
my ($kernel, $time) = @_[KERNEL, ARG0];
$kernel->yield("sleeper", $time);
}

sub sleeper {
my ($kernel, $session, $time)
= @_[KERNEL, SESSION, ARG0];
print "Hello OSCon Attendees!\n";
$kernel->delay_set("sleeper", $time, $time);
}

You can see there are 2 states – first one (start) is used just one to plan immediate (read: as soon as possible) run of seeper state/subrutine. That one is planed again at some specified time.

Tags

Napsat komentář