Iterate at some later point
use CPS qw( gkforeach ); use CPS::Governor::Deferred; my $gov = CPS::Governor::Deferred->new; gkforeach( $gov, [ 1 .. 10 ], sub { my ( $item, $knext ) = @_; print "A$item "; goto &$knext; }, sub {}, ); gkforeach( $gov, [ 1 .. 10 ], sub { my ( $item, $knext ) = @_; print "B$item "; goto &$knext; }, sub {}, ); $gov->flush;
This CPS::Governor allows the functions using it to delay their iteration until some later point when the containing program invokes it. This allows two main advantages:
CPU-intensive operations may be split apart and mixed with other \s-1IO\s0 operations
Multiple control functions may be executed in pseudo-parallel, interleaving iterations of each giving a kind of concurrency
These are achieved by having the governor store a list of code references that need to be invoked, rather than invoking them immediately. These references can then be invoked later, perhaps by using an idle watcher in an event framework.
Because each code reference hasn't yet been invoked by the time the \*(C`again\*(C' method is called, the original caller is free to store more pending references with the governor. This allows multiple control functions to be interleaved, as in the \*(C`A\*(C' and \*(C`B\*(C' example above.
Returns a new instance of a \*(C`CPS::Governor::Deferred\*(C' object. Requires no parameters but may take any of the following to adjust its default behaviour:
If given some positive number, $n then the first \*(C`$n-1\*(C' invocations of the \*(C`again\*(C' method will in fact be executed immediately. Thereafter they will be enqueued in the normal mechanism. This gives the effect that longrunning loops will be executed in batches of $n. If not supplied then every invocation of \*(C`again\*(C' will use the queueing mechanism.
Returns true if at least one code reference has been stored that hasn't yet been invoked. Invokes all of the currently-stored code references, in the order they were stored. If any new references are stored by these, they will not yet be invoked, but will be available for the next time this method is called. Repeatedly calls \*(C`prod\*(C' until no more code references are pending.
The following methods are used internally to implement the functionality, which may be useful to implementors of subclasses. Used to enqueue the $code ref to be invoked later with the given @args, once it is determined this should be deferred (rather than being invoked immediately in the case of the first few invocations when \*(C`defer_after\*(C' is set).
Paul Evans <[email protected]>