1IO::Async::Function(3)User Contributed Perl DocumentationIO::Async::Function(3)
2
3
4

NAME

6       "IO::Async::Function" - call a function asynchronously
7

SYNOPSIS

9        use IO::Async::Function;
10
11        use IO::Async::Loop;
12        my $loop = IO::Async::Loop->new;
13
14        my $function = IO::Async::Function->new(
15           code => sub {
16              my ( $number ) = @_;
17              return is_prime( $number );
18           },
19        );
20
21        $loop->add( $function );
22
23        $function->call(
24           args => [ 123454321 ],
25        )->on_done( sub {
26           my $isprime = shift;
27           print "123454321 " . ( $isprime ? "is" : "is not" ) . " a prime number\n";
28        })->on_fail( sub {
29           print STDERR "Cannot determine if it's prime - $_[0]\n";
30        })->get;
31

DESCRIPTION

33       This subclass of IO::Async::Notifier wraps a function body in a
34       collection of worker processes, to allow it to execute independently of
35       the main process.  The object acts as a proxy to the function, allowing
36       invocations to be made by passing in arguments, and invoking a
37       continuation in the main process when the function returns.
38
39       The object represents the function code itself, rather than one
40       specific invocation of it. It can be called multiple times, by the
41       "call" method.  Multiple outstanding invocations can be called; they
42       will be dispatched in the order they were queued. If only one worker
43       process is used then results will be returned in the order they were
44       called. If multiple are used, then each request will be sent in the
45       order called, but timing differences between each worker may mean
46       results are returned in a different order.
47
48       Since the code block will be called multiple times within the same
49       child process, it must take care not to modify any of its state that
50       might affect subsequent calls. Since it executes in a child process, it
51       cannot make any modifications to the state of the parent program.
52       Therefore, all the data required to perform its task must be
53       represented in the call arguments, and all of the result must be
54       represented in the return values.
55
56       The Function object is implemented using an IO::Async::Routine with two
57       IO::Async::Channel objects to pass calls into and results out from it.
58
59       The IO::Async framework generally provides mechanisms for multiplexing
60       IO tasks between different handles, so there aren't many occasions when
61       such an asynchronous function is necessary. Two cases where this does
62       become useful are:
63
64       1.  When a large amount of computationally-intensive work needs to be
65           performed (for example, the "is_prime" test in the example in the
66           "SYNOPSIS").
67
68       2.  When a blocking OS syscall or library-level function needs to be
69           called, and no nonblocking or asynchronous version is supplied.
70           This is used by IO::Async::Resolver.
71
72       This object is ideal for representing "pure" functions; that is, blocks
73       of code which have no stateful effect on the process, and whose result
74       depends only on the arguments passed in. For a more general co-routine
75       ability, see also IO::Async::Routine.
76

PARAMETERS

78       The following named parameters may be passed to "new" or "configure":
79
80   code => CODE
81       The body of the function to execute.
82
83        @result = $code->( @args )
84
85   init_code => CODE
86       Optional. If defined, this is invoked exactly once in every child
87       process or thread, after it is created, but before the first invocation
88       of the function body itself.
89
90        $init_code->()
91
92   model => "fork" | "thread"
93       Optional. Requests a specific IO::Async::Routine model. If not
94       supplied, leaves the default choice up to Routine.
95
96   min_workers => INT
97   max_workers => INT
98       The lower and upper bounds of worker processes to try to keep running.
99       The actual number running at any time will be kept somewhere between
100       these bounds according to load.
101
102   max_worker_calls => INT
103       Optional. If provided, stop a worker process after it has processed
104       this number of calls. (New workers may be started to replace stopped
105       ones, within the bounds given above).
106
107   idle_timeout => NUM
108       Optional. If provided, idle worker processes will be shut down after
109       this amount of time, if there are more than "min_workers" of them.
110
111   exit_on_die => BOOL
112       Optional boolean, controls what happens after the "code" throws an
113       exception. If missing or false, the worker will continue running to
114       process more requests. If true, the worker will be shut down. A new
115       worker might be constructed by the "call" method to replace it, if
116       necessary.
117
118   setup => ARRAY
119       Optional array reference. Specifies the "setup" key to pass to the
120       underlying IO::Async::Process when setting up new worker processes.
121

METHODS

123       The following methods documented with a trailing call to "->get" return
124       Future instances.
125
126   start
127          $function->start
128
129       Start the worker processes
130
131   stop
132          $function->stop
133
134       Stop the worker processes
135
136   restart
137          $function->restart
138
139       Gracefully stop and restart all the worker processes.
140
141   call
142          @result = $function->call( %params )->get
143
144       Schedules an invocation of the contained function to be executed on one
145       of the worker processes. If a non-busy worker is available now, it will
146       be called immediately. If not, it will be queued and sent to the next
147       free worker that becomes available.
148
149       The request will already have been serialised by the marshaller, so it
150       will be safe to modify any referenced data structures in the arguments
151       after this call returns.
152
153       The %params hash takes the following keys:
154
155       args => ARRAY
156               A reference to the array of arguments to pass to the code.
157
158       priority => NUM
159               Optional. Defines the sorting order when no workers are
160               available and calls must be queued for later. A default of zero
161               will apply if not provided.
162
163               Higher values cause the call to be considered more important,
164               and will be placed earlier in the queue than calls with a
165               smaller value. Calls of equal priority are still handled in
166               FIFO order.
167
168       If the function body returns normally the list of results are provided
169       as the (successful) result of returned future. If the function throws
170       an exception this results in a failed future. In the special case that
171       the exception is in fact an unblessed "ARRAY" reference, this array is
172       unpacked and used as-is for the "fail" result. If the exception is not
173       such a reference, it is used as the first argument to "fail", in the
174       category of "error".
175
176          $f->done( @result )
177
178          $f->fail( @{ $exception } )
179          $f->fail( $exception, error => )
180
181   call (void)
182          $function->call( %params )
183
184       When not returning a future, the "on_result", "on_return" and
185       "on_error" arguments give continuations to handle successful results or
186       failure.
187
188       on_result => CODE
189               A continuation that is invoked when the code has been executed.
190               If the code returned normally, it is called as:
191
192                $on_result->( 'return', @values )
193
194               If the code threw an exception, or some other error occurred
195               such as a closed connection or the process died, it is called
196               as:
197
198                $on_result->( 'error', $exception_name )
199
200       on_return => CODE and on_error => CODE
201               An alternative to "on_result". Two continuations to use in
202               either of the circumstances given above. They will be called
203               directly, without the leading 'return' or 'error' value.
204
205   workers
206          $count = $function->workers
207
208       Returns the total number of worker processes available
209
210   workers_busy
211          $count = $function->workers_busy
212
213       Returns the number of worker processes that are currently busy
214
215   workers_idle
216          $count = $function->workers_idle
217
218       Returns the number of worker processes that are currently idle
219

EXAMPLES

221   Extended Error Information on Failure
222       The array-unpacking form of exception indiciation allows the function
223       body to more precicely control the resulting failure from the "call"
224       future.
225
226        my $divider = IO::Async::Function->new(
227           code => sub {
228              my ( $numerator, $divisor ) = @_;
229              $divisor == 0 and
230                 die [ "Cannot divide by zero", div_zero => $numerator, $divisor ];
231
232              return $numerator / $divisor;
233           }
234        );
235

NOTES

237       For the record, 123454321 is 11111 * 11111, a square number, and
238       therefore not prime.
239

AUTHOR

241       Paul Evans <leonerd@leonerd.org.uk>
242
243
244
245perl v5.30.0                      2019-07-26            IO::Async::Function(3)
Impressum