1POE::Session(3) User Contributed Perl Documentation POE::Session(3)
2
3
4
6 POE::Session - an event driven abstract state machine
7
9 # Import POE::Session constants.
10 use POE::Session;
11
12 POE::Session->create(
13
14 # Inline or coderef states.
15 inline_states => {
16 state_one => \&coderef_one,
17 state_two => sub { ... },
18 },
19
20 # Plain and mapped object states.
21 object_states => [
22 $object_one => [ 'state_three', 'state_four', 'state_five' ],
23 $object_two => { state_nine => 'method_nine' },
24 ],
25
26 # Plain and mapped package states.
27 package_states => [
28 $package_one => [ 'state_six', 'state_seven', 'state_eight' ],
29 $package_two => { state_ten => 'method_ten' },
30 ],
31
32 # Parameters for the session's _start state.
33 args => [ argument_zero, argument_one, ... ],
34
35 # Initial options. See the option() method.
36 options => \%options,
37
38 # Change the session's heap representation.
39 heap => [ ],
40 );
41
42 Other methods:
43
44 # Retrieve a session's unique identifier.
45 $session_id = $session->ID;
46
47 # Retrieve a reference to the session's heap.
48 $session_heap = $session->get_heap();
49
50 # Set or clear session options.
51 $session->option( trace => 1, default => 1 );
52 $session->option( trace );
53
54 # Create a postback, then invoke it and pass back additional
55 # information.
56 $postback_coderef = $session->postback( $state_name, @state_args );
57 $postback_coderef->( @additional_args );
58
59 # Or do the same thing synchronously
60 $callback_coderef = $session->callback( $state_name, @state_args );
61 $retval = $callback_coderef->( @additional_args );
62
64 POE::Session combines a runtime context with an event driven state
65 machine. Together they implement a simple cooperatively timesliced
66 thread.
67
68 Sessions receive their timeslices as events from POE::Kernel. Each
69 event has two fields, a state name and a session identifier. These
70 fields describe the code to run and the context to run it in, respec‐
71 tively. Events carry several other fields which will be discussed in
72 the "Predefined Event Fields" section.
73
74 States are re-entrant since they are invoked with their runtime con‐
75 texts. Although it's not usually necessary, this re-entrancy allows a
76 single function to be bound to several different sessions, under sev‐
77 eral different state names.
78
79 As sessions run, they post new events through the Kernel. These events
80 may be for themselves or other sessions, in which case they act as a
81 form of inter-session communications. The Kernel can also generate
82 events based on external conditions such as file activity or the pas‐
83 sage of time.
84
85 POE provides some convenient built-in states with special meanings.
86 They will be covered later on in the "Predefined States" section.
87
89 ID
90 ID() returns the session instance's unique identifier. This is a
91 number that starts with 1 and counts up forever, or until something
92 causes the number to wrap. It's theoretically possible that session
93 IDs may collide after about 4.29 billion sessions have been created.
94
95 create LOTS_OF_STUFF
96 create() is the recommended Session constructor. It binds states to
97 their corresponding event names, initializes other parts of the ses‐
98 sion, and then fires off its "_start" state, possibly with some
99 parameters.
100
101 create's parameters look like a hash of name/value pairs, but it's
102 really just a list. This is so the the constructor can unambiguously
103 recognize and validate parameters and the programmer/maintainers know
104 what events is being dispatched to what.
105
106 "create()" returns a reference to the newly created session but it is
107 recommended not to save this. POE::Kernel manages sessions and will
108 ensure timely destruction of them as long as extra references to them
109 aren't hanging around.
110
111 args => ARRAYREF
112 The "args" parameter accepts a reference to a list of parameters
113 that will be passed to the machine's "_start" state. They are
114 passed in the "_start" event's "ARG0..$#_" fields.
115
116 args => [ 'arg0', 'arg1', 'etc.' ],
117
118 sub _start {
119 my @args = @_[ARG0..#$_];
120 print "I received these parameters from create()'s args: @args\n";
121 }
122
123 heap => ANYTHING
124 The "heap" parameter defines a session's heap. The heap is passed
125 into states as the $_[HEAP] field. Heaps are anonymous hash refer‐
126 ences by default.
127
128 POE::Session->create( ..., heap => { runstate_variable => 1 }, ... );
129
130 sub state_function {
131 my $heap = $_[HEAP];
132 print "runstate variable is $heap->{runstate_variable}\n";
133 }
134
135 It's also possible to use create's "heap" parameter to change the
136 heap into something completely different, such as a list reference
137 or even an object.
138
139 sub RUNSTATE_VARIABLE () { 0 } # offset into the heap
140 POE::Session->create( ..., heap => [ 1 ], ... );
141
142 sub state_function {
143 my $heap = $_[HEAP];
144 print "runstate variable is ", $heap->[RUNSTATE_VARIABLE], "\n";
145 }
146
147 inline_states => HASHREF
148 "inline_states" maps events names to the plain coderefs which will
149 handle them. Its value is a reference to a hash of event names and
150 corresponding coderefs.
151
152 inline_states => {
153 _start => sub { print "arg0=$_[ARG0], arg1=$_[ARG1], etc.=$_[ARG2]\n"; }
154 _stop => \&stop_handler,
155 },
156
157 These states are called "inline" because they can be inline anony‐
158 mous subs.
159
160 object_states => ARRAYREF
161 "object_states" maps event names to the object methods which will
162 handle them. Its value is a arrayref of object references and the
163 methods to use. It's a arrayref because using a hashref would
164 stringify its keys, and the object references would become unus‐
165 able.
166
167 The object's methods can be specified in two ways.
168
169 The first form associates a arrayref to each object reference.
170 This form maps each event to an object method with the same name.
171 In this example, "event_one" is handled by $object's "event_one()"
172 method.
173
174 object_states => [
175 $object => [ 'event_one', 'event_two' ],
176 ];
177
178 The second form associates a hashref to each object reference. In
179 turn, the hashref maps each event name to a method in the object.
180 In this form, the object's method names needn't match the event
181 names they'll handle. For example, "event_four" is handled by
182 $object's "handler_four()" method.
183
184 object_states => [
185 $object => {
186 event_three => 'handler_three',
187 event_four => 'handler_four',
188 }
189 ];
190
191 options => HASHREF
192 "options" contains a new session's initial options. It's equiva‐
193 lent to creating the session and then calling its option() method
194 to set them. HASHREF contains a set of option/value pairs.
195
196 These two statements are equivalent:
197
198 POE::Session->create(
199 ...,
200 options => { trace => 1, debug => 1 },
201 ...,
202 );
203
204 POE::Session->create(
205 ...,
206 )->option( trace => 1, debug => 1 );
207
208 See the option() method for a list of options and values.
209
210 package_states => ARRAYREF
211 "package_states" maps event names to the package methods which will
212 handle them. It's very similar to "object_states". "pack‐
213 age_states"' value is a arrayref of package names and the methods
214 to use. It's a arrayref for consistency with "object_states".
215
216 The package's methods can be specified in two ways.
217
218 The first form associates a arrayref to each package name. This
219 form maps each event to a package method with the same name. In
220 this example, "event_ten" is handled by "Package"'s "event_ten()"
221 method.
222
223 package_states => [
224 Package => [ 'event_ten', 'event_eleven' ],
225 ];
226
227 The second form associates a hashref to each package name. In
228 turn, the hashref maps each event name to a method in the package.
229 In this form, the package's method names needn't match the event
230 names they'll handle. For example, "event_twelve" is handled by
231 "Package"'s "handler_twelve()" method.
232
233 package_states => [
234 Package => {
235 event_twelve => 'handler_twelve',
236 event_thirteen => 'handler_thirteen',
237 }
238 ];
239
240 option OPTION_NAME
241 option OPTION_NAME, OPTION_VALUE
242 option NAME_VALUE_PAIR_LIST
243 "option()" sets and/or retrieves options' values.
244
245 The first form returns the value of a single option, OPTION_NAME,
246 without changing it.
247
248 my $trace_value = $_[SESSION]->option( 'trace' );
249
250 The second form sets OPTION_NAME to OPTION_VALUE, returning the pre‐
251 vious value of OPTION_NAME.
252
253 my $old_trace_value = $_[SESSION]->option( trace => $new_trace_value );
254
255 The final form sets several options, returning a hashref containing
256 pairs of option names and their previous values.
257
258 my $old_values = $_[SESSION]->option( trace => $new_trace_value,
259 debug => $new_debug_value,
260 );
261 print "Old option values:\n";
262 while (my ($option, $old_value) = each %$old_values) {
263 print "$option = $old_value\n";
264 }
265
266 postback EVENT_NAME, EVENT_PARAMETERS
267 callback EVENT_NAME, EVENT_PARAMETERS
268 postback() and callback() create anonymous coderefs that may be used
269 as callbacks for other libraries. A contrived example:
270
271 my $postback = $session->postback( event_one => 1, 2, 3 );
272 my $callback = $session->callback( event_two => 5, 6, 7 );
273
274 use File::Find;
275 find( $callback, @directories_to_search );
276
277 $poe_main_window->Button(
278 -text => 'Begin Slow and Fast Alarm Counters',
279 -command => $postback,
280 )->pack;
281
282 When called, postbacks and callbacks fire POE events. Postbacks use
283 $kernel->post(), and callbacks use $kernel->call(). See POE::Kernel
284 for post() and call() documentation.
285
286 Each takes an EVENT_NAME, which is the name of the event to fire when
287 called. Any other EVENT_PARAMETERS are passed to the event's handler
288 as a list reference in ARG0.
289
290 Calling "<$postback-"("a", "b", "c")>> results in event_one's handler
291 being called with the following arguments:
292
293 sub handle_event_one {
294 my $passed_through = $_[ARG0]; # [ 1, 2, 3 ]
295 my $passed_back = $_[ARG1]; # [ "a", "b", "c" ]
296 }
297
298 Calling "<$callback-"("m", "n", "o")>> does the same:
299
300 sub handle_event_two {
301 my $passed_through = $_[ARG0]; # [ 5, 6, 7 ]
302 my $passed_back = $_[ARG1]; # [ "m", "n", "o" ]
303 }
304
305 Therefore you can use ARG0 to pass state through a callback, while
306 ARG1 contains information provided by the external library to its
307 callbacks.
308
309 Postbacks and callbacks use reference counts to keep the sessions
310 they are called upon alive. This prevents sessions from disappearing
311 while other code expects them to handle callbacks. The Tk Button
312 code above is an example of this in action. The session will not
313 stop until the widget releases its postback.
314
315 The difference between postback() and callback() is subtle but can
316 cause all manner of grief if you are not aware of it. Postback han‐
317 dlers are not called right away since they are triggered by events
318 posted through the queue. Callback handlers are invoked immediately
319 since they are triggered by call().
320
321 Some libraries expect their callbacks to be invoked immediately.
322 They may go so far as to set up global variables for the duration of
323 the callback. File::Find is such a library. Each callback receives
324 a new filename in $_. Delaying these callbacks until later means
325 that $_ will not contain expected values. It is necessary to use
326 callback() in these cases.
327
328 Most libraries pass state to their callbacks as parameters. Gener‐
329 ally, postback() is the way to go.
330
331 Since postback() and callback() are Session methods, they may be
332 called on $_[SESSION] or $_[SENDER], depending on particular needs.
333 There are usually better ways to interact between sessions, however.
334
335 get_heap
336 "get_heap()" returns a reference to a session's heap. It's the same
337 value that's passed to every state via the "HEAP" field, so it's not
338 necessary within states.
339
340 Combined with the Kernel's "get_active_session()" method,
341 "get_heap()" lets libraries access a Session's heap without having to
342 be given it. It's convenient, for example, to write a function like
343 this:
344
345 sub put_stuff {
346 my @stuff_to_put = @_;
347 $poe_kernel->get_active_session()->get_heap()->{wheel}->put(
348 @stuff_to_put
349 );
350 }
351
352 sub some_state {
353 ...;
354 &put_stuff( @stuff_to_put );
355 }
356
357 While it's more efficient to pass "HEAP" along, it's also less conve‐
358 nient.
359
360 sub put_stuff {
361 my ($heap, @stuff_to_put) = @_;
362 $heap->{wheel}->put( @stuff_to_put );
363 }
364
365 sub some_state {
366 ...;
367 &put_stuff( $_[HEAP], @stuff_to_put );
368 }
369
370 Although if you expect to have a lot of calls to &put_a_wheel() in
371 your program, you may want to optimize for programmer efficiency by
372 using the first form.
373
374 Subclassing
375
376 There are a few methods available to help people trying to subclass
377 POE::Session.
378
379 instantiate
380 When you want to subclass POE::Session, you may want to allow for
381 extra parameters to be passed to the constructor, and maybe store
382 some extra data in the object structure.
383
384 The easiest way to do this is by overriding the instantiate method,
385 which creates an empty object for you, and is passed a reference to
386 the hash of parameters passed to create().
387
388 When overriding it, be sure to first call the parent classes instan‐
389 tiate method, so you have a reference to the empty object. Then you
390 should remove all the extra parameters from the hash of parameters
391 you get passed, so POE::Session's create() doesn't croak when it
392 encounters parameters it doesn't know.
393
394 Also, don't forget to return the reference to the object (optionally
395 already filled with your data; try to keep out of the places where
396 POE::Session stores its stuff, or it'll get overwritten)
397
398 try_alloc
399 At the end of POE::Session's create() method, try_alloc() is called.
400 This tells the POE Kernel to allocate an actual session with the
401 object just created.
402
403 If you want to fiddle with the object the constructor just created,
404 to modify parameters that already exist in the base POE::Session
405 class, based on your extra parameters for example, this is the place
406 to do it. override the try_alloc() method, do your evil, and end
407 with calling the parent try_alloc(), returning its return value.
408
409 try_alloc() is passed the arguments for the _start state (the con‐
410 tents of the listref passed in the 'args' parameter for create()).
411 Make sure to pass this on to the parent method (after maybe fiddling
412 with that too).
413
415 Each session maintains its unique runtime context. Sessions pass their
416 contexts on to their states through a series of standard parameters.
417 These parameters tell each state about its Kernel, its Session, itself,
418 and the events that invoke it.
419
420 State parameters' offsets into @_ are never used directly. Instead
421 they're referenced by symbolic constant. This lets POE to change their
422 order without breaking programs, since the constants will always be
423 correct.
424
425 These are the @_ fields that make up a session's runtime context.
426
427 ARG0
428 ARG1
429 ARG2
430 ARG3
431 ARG4
432 ARG5
433 ARG6
434 ARG7
435 ARG8
436 ARG9
437 "ARG0..ARG9" are a state's first ten custom parameters. They will
438 always be at the end of @_, so it's possible to access more than ten
439 parameters with $_[ARG9+1] or even this:
440
441 my @args = @_[ARG0..$#_];
442
443 The custom parameters often correspond to PARAMETER_LIST in many of
444 the Kernel's methods. This passes the words "zero" through "four" to
445 "some_state" as @_[ARG0..ARG4]:
446
447 $_[KERNEL]->yield( some_state => qw( zero one two three four ) );
448
449 Only "ARG0" is really needed. "ARG1" is just "ARG0+1", and so on.
450
451 HEAP
452 "HEAP" is a session's unique runtime storage space. It's separate
453 from everything else so that Session authors don't need to worry
454 about namespace collisions.
455
456 States that store their runtime values in the "HEAP" will always be
457 saving it in the correct session. This makes them re-entrant, which
458 will be a factor when Perl's threading stops being experimental.
459
460 sub _start {
461 $_[HEAP]->{start_time} = time();
462 }
463
464 sub _stop {
465 my $elapsed_runtime = time() - $_[HEAP]->{start_time};
466 print 'Session ', $_[SESSION]->ID, " elapsed runtime: $elapsed_runtime\n";
467 }
468
469 KERNEL
470 "KERNEL" is a reference to the Kernel. It's used to access the Ker‐
471 nel's methods from within states.
472
473 # Fire a "time_is_up" event in ten seconds.
474 $_[KERNEL]->delay( time_is_up => 10 );
475
476 It can also be used with "SENDER" to make sure Kernel events have
477 actually come from the Kernel.
478
479 OBJECT
480 "OBJECT" is only meaningful in object and package states.
481
482 In object states, it contains a reference to the object whose method
483 is being invoked. This is useful for invoking plain object methods
484 once an event has arrived.
485
486 sub ui_update_everything {
487 my $object = $_[OBJECT];
488 $object->update_menu();
489 $object->update_main_window();
490 $object->update_status_line();
491 }
492
493 In package states, it contains the name of the package whose method
494 is being invoked. Again, it's useful for invoking plain package
495 methods once an event has arrived.
496
497 sub Package::_stop {
498 $_[PACKAGE]->shutdown();
499 }
500
501 "OBJECT" is undef in inline states.
502
503 SENDER
504 "SENDER" is a reference to the session that sent an event. It can be
505 used as a return address for service requests. It can also be used
506 to validate events and ignore them if they've come from unexpected
507 places.
508
509 This example shows both common uses. It posts a copy of an event
510 back to its sender unless the sender happens to be itself. The con‐
511 dition is important in preventing infinite loops.
512
513 sub echo_event {
514 $_[KERNEL]->post( $_[SENDER], $_[STATE], @_[ARG0..$#_] )
515 unless $_[SENDER] == $_[SESSION];
516 }
517
518 SESSION
519 "SESSION" is a reference to the current session. This lets states
520 access their own session's methods, and it's a convenient way to
521 determine whether "SENDER" is the same session.
522
523 sub enable_trace {
524 $_[SESSION]->option( trace => 1 );
525 print "Session ", $_[SESSION]->ID, ": dispatch trace is now on.\n";
526 }
527
528 STATE
529 "STATE" contains the event name that invoked a state. This is useful
530 in cases where a single state handles several different events.
531
532 sub some_state {
533 print(
534 "some_state in session ", $_[SESSION]->ID,
535 " was invoked as ", $_[STATE], "\n"
536 );
537 }
538
539 POE::Session->create(
540 inline_states => {
541 one => \&some_state,
542 two => \&some_state,
543 six => \&some_state,
544 ten => \&some_state,
545 }
546 );
547
548 CALLER_FILE
549 CALLER_LINE
550 CALLER_STATE
551 my ($caller_file, $caller_line, $caller_state) =
552 @_[CALLER_FILE, CALLER_LINE, CALLER_STATE];
553
554 The file, line number, and state from which this state was called.
555
557 POE contains helpers which, in order to help, need to emit predefined
558 events. These events all begin with a single leading underscore, and
559 it's recommended that sessions not post leading-underscore events
560 unless they know what they're doing.
561
562 Predefined events generally have serious side effects. The "_start"
563 event, for example, performs a lot of internal session initialization.
564 Posting a redundant "_start" event may try to allocate a session that
565 already exists, which in turn would do terrible, horrible things to the
566 Kernel's internal data structures. Such things would normally be out‐
567 lawed outright, but the extra overhead to check for them would slow
568 everything down all the time. Please be careful! The clock cycles you
569 save may be your own.
570
571 These are the predefined events, why they're emitted, and what their
572 parameters mean.
573
574 _child
575 "_child" is a job-control event. It notifies a parent session when
576 its set of child sessions changes.
577
578 "ARG0" contains one of three strings describing what is happening to
579 the child session.
580
581 'create'
582 A child session has just been created, and the current session is
583 its original parent.
584
585 'gain'
586 This session is gaining a new child from a child session that has
587 stopped. A grandchild session is being passed one level up the
588 inheritance tree.
589
590 'lose'
591 This session is losing a child which has stopped.
592
593 "ARG1" is a reference to the child session. It will still be valid,
594 even if the child is in its death throes, but it won't last long
595 enough to receive posted events. If the parent must interact with
596 this child, it should do so with "call()" or some other means.
597
598 "ARG2" is only valid when a new session has been created or an old
599 one destroyed. It holds the return value from the child session's
600 "_start" or "_stop" state when "ARG0" is 'create' or 'lose', respec‐
601 tively.
602
603 _default
604 "_default" is the event that's delivered whenever an event isn't han‐
605 dled. The unhandled event becomes parameters for "_default".
606
607 It's perfectly okay to post events to a session that can't handle
608 them. When this occurs, the session's "_default" handler is invoked
609 instead. If the session doesn't have a "_default" handler, then the
610 event is quietly discarded.
611
612 Quietly discarding events is a feature, but it makes catching
613 mistyped event names kind of hard. There are a couple ways around
614 this: One is to define event names as symbolic constants. Perl will
615 catch typos at compile time. The second way around it is to turn on
616 a session's "debug" option (see Session's "option()" method). This
617 makes unhandled events hard runtime errors.
618
619 As was previously mentioned, unhandled events become "_default"'s
620 parameters. The original state's name is preserved in "ARG0" while
621 its custom parameter list is preserved as a reference in "ARG1".
622
623 sub _default {
624 print "Default caught an unhandled $_[ARG0] event.\n";
625 print "The $_[ARG0] event was given these parameters: @{$_[ARG1]}\n";
626 }
627
628 All the other "_default" parameters are the same as the unhandled
629 event's, with the exception of "STATE", which becomes "_default".
630
631 POE::Kernel discusses signal handlers in "Signal Watcher Methods".
632 It also covers the pitfalls of "_default" states in more detail
633
634 _parent
635 "_parent" It notifies child sessions that their parent sessions are
636 in the process of changing. It is the complement to "_child".
637
638 "ARG0" contains the session's previous parent, and "ARG1" contains
639 its new parent.
640
641 _start
642 "_start" is a session's initialization event. It tells a session
643 that the Kernel has allocated and initialized resources for it, and
644 it may now start doing things. A session's constructors invokes the
645 "_start" handler before it returns, so it's possible for some ses‐
646 sions' "_start" states to run before $poe_kernel->run() is called.
647
648 Every session must have a "_start" handler. Its parameters are
649 slightly different from normal ones.
650
651 "SENDER" contains a reference to the new session's parent. Sessions
652 created before $poe_kernel->run() is called will have "KERNEL" as
653 their parents.
654
655 "ARG0..$#_" contain the parameters passed into the Session's con‐
656 structor. See Session's "create()" method for more information on
657 passing parameters to new sessions.
658
659 _stop
660 "_stop" is sent to a session when it's about to stop. This usually
661 occurs when a session has run out of events to handle and resources
662 to generate new events.
663
664 The "_stop" handler is used to perform shutdown tasks, such as
665 releasing custom resources and breaking circular references so that
666 Perl's garbage collection will properly destroy things.
667
668 Because a session is destroyed after a "_stop" handler returns, any
669 POE things done from a "_stop" handler may not work. For example,
670 posting events from "_stop" will be ineffective since part of the
671 Session cleanup is removing posted events.
672
673 Signal Events
674 "ARG0" contains the signal's name as it appears in Perl's %SIG hash.
675 That is, it is the root name of the signal without the SIG prefix.
676 POE::Kernel discusses exceptions to this, namely that CLD will be
677 presented as CHLD.
678
679 The "Signal Watcher Methods" section in POE::Kernel is recommended
680 reading before using signal events. It discusses the different sig‐
681 nal levels and the mechanics of signal propagation.
682
684 States' Return Values
685
686 States are always evaluated in a scalar context. States that must
687 return more than one value should therefore return them as a reference
688 to something bigger.
689
690 States may not return references to objects in the "POE" namespace.
691 The Kernel will stringify these references to prevent them from linger‐
692 ing and breaking its own garbage collection.
693
694 Resource Tracking
695
696 POE::Kernel tracks resources on behalf of its active sessions. It gen‐
697 erates events corresponding to these resources' activity, notifying
698 sessions when it's time to do things.
699
700 The conversation goes something like this.
701
702 Session: Be a dear, Kernel, and let me know when someone clicks on
703 this widget. Thanks so much!
704
705 [TIME PASSES] [SFX: MOUSE CLICK]
706
707 Kernel: Right, then. Someone's clicked on your widget.
708 Here you go.
709
710 Furthermore, since the Kernel keeps track of everything sessions do, it
711 knows when a session has run out of tasks to perform. When this hap‐
712 pens, the Kernel emits a "_stop" event at the dead session so it can
713 clean up and shutdown.
714
715 Kernel: Please switch off the lights and lock up; it's time to go.
716
717 Likewise, if a session stops on its own and there still are opened
718 resource watchers, the Kernel knows about them and cleans them up on
719 the session's behalf. POE excels at long-running services because it
720 so meticulously tracks and cleans up its resources.
721
722 Synchronous and Asynchronous Events
723
724 While time's passing, however, the Kernel may be telling Session other
725 things are happening. Or it may be telling other Sessions about things
726 they're interested in. Or everything could be quiet... perhaps a lit‐
727 tle too quiet. Such is the nature of non-blocking, cooperative times‐
728 licing, which makes up the heart of POE's threading.
729
730 Some resources must be serviced right away, or they'll faithfully con‐
731 tinue reporting their readiness. These reports would appear as a
732 stream of duplicate events, which would be bad. These are "synchro‐
733 nous" events because they're handled right away.
734
735 The other kind of event is called "asynchronous" because they're posted
736 and dispatched through a queue. There's no telling just when they'll
737 arrive.
738
739 Synchronous event handlers should perform simple tasks limited to han‐
740 dling the resources that invoked them. They are very much like device
741 drivers in this regard.
742
743 Synchronous events that need to do more than just service a resource
744 should pass the resource's information to an asynchronous handler.
745 Otherwise synchronous operations will occur out of order in relation to
746 asynchronous events. It's very easy to have race conditions or break
747 causality this way, so try to avoid it unless you're okay with the con‐
748 sequences.
749
750 Postbacks
751
752 Many external libraries expect plain coderef callbacks, but sometimes
753 programs could use asynchronous events instead. POE::Session's "post‐
754 back()" method was created to fill this need.
755
756 "postback()" creates coderefs suitable to be used in traditional call‐
757 backs. When invoked as callbacks, these coderefs post their parameters
758 as POE events. This lets POE interact with nearly every callback cur‐
759 rently in existence, and most future ones.
760
761 Job Control and Family Values
762
763 Sessions are resources, too. The Kernel watches sessions come and go,
764 maintains parent/child relationships, and notifies sessions when these
765 relationships change. These events, "_parent" and "_child", are useful
766 for job control and managing pools of worker sessions.
767
768 Parent/child relationships are maintained automatically. "Child" ses‐
769 sions simply are ones which have been created from an existing session.
770 The existing session which created a child becomes its "parent".
771
772 A session with children will not spontaneously stop. In other words,
773 the presence of child sessions will keep a parent alive.
774
775 Exceptions
776
777 POE traps exceptions that happen within an event. When an exception
778 occurs, POE sends the "DIE" signal to the session that caused the
779 exception. This is a terminal signal and will shutdown the POE environ‐
780 ment unless the session handles the signal and calls "sig_handled()".
781
782 This behavior can be turned off by setting the "CATCH_EXCEPTIONS" con‐
783 stant subroutine in "POE::Kernel" to 0 like so:
784
785 sub POE::Kernel::CATCH_EXCEPTIONS () { 0 }
786
787 The signal handler will be passed a single argument, a hashref, con‐
788 taining the following data.
789
790 source_session
791 The session from which the event originated
792
793 dest_session
794 The session which was the destination of the event. This is also the
795 session that caused the exception.
796
797 event
798 Name of the event that caused the exception
799
800 file
801 The filename of the code which called the problematic event
802
803 line
804 The line number of the code which called the problematic event
805
806 from_state
807 The state that was called the problematci event
808
809 error_str
810 The value of $@, which contains the error string created by the
811 exception.
812
813 Session's Debugging Features
814
815 POE::Session contains a two debugging assertions, for now.
816
817 ASSERT_DEFAULT
818 ASSERT_DEFAULT is used as the default value for all the other assert
819 constants. Setting it true is a quick and reliably way to ensure all
820 Session assertions are enabled.
821
822 Session's ASSERT_DEFAULT inherits Kernel's ASSERT_DEFAULT value
823 unless overridden.
824
825 ASSERT_STATES
826 Setting ASSERT_STATES to true causes every Session to warn when they
827 are asked to handle unknown events. Session.pm implements the guts
828 of ASSERT_STATES by defaulting the "default" option to true instead
829 of false. See the option() function earlier in this document for
830 details about the "default" option.
831
833 POE::Kernel.
834
835 The SEE ALSO section in POE contains a table of contents covering the
836 entire POE distribution.
837
839 There is a chance that session IDs may collide after Perl's integer
840 value wraps. This can occur after as few as 4.29 billion sessions.
841
843 Please see POE for more information about authors and contributors.
844
845
846
847perl v5.8.8 2006-09-01 POE::Session(3)