1IO::Async::Function(3)User Contributed Perl DocumentationIO::Async::Function(3)
2
3
4
6 "IO::Async::Function" - call a function asynchronously
7
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
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
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 module => STRING
93 func => STRING
94 Since version 0.79.
95
96 An alternative to the "code" argument, which names a module to load and
97 a function to call within it. "module" should give a perl module name
98 (i.e. "Some::Name", not a filename like Some/Name.pm), and "func"
99 should give the basename of a function within that module (i.e. without
100 the module name prefixed). It will be invoked, without extra arguments,
101 as the main code body of the object.
102
103 The task of loading this module and resolving the resulting function
104 from it is only performed on the remote worker side, so the controlling
105 process will not need to actually load the module.
106
107 init_func => STRING or ARRAY [ STRING, ... ]
108 Optional addition to the "module" and "func" alternatives. Names a
109 function within the module to call each time a new worker is created.
110
111 If this value is an array reference, its first element must be a string
112 giving the name of the function; the remaining values are passed to
113 that function as arguments.
114
115 model => "fork" | "thread" | "spawn"
116 Optional. Requests a specific IO::Async::Routine model. If not
117 supplied, leaves the default choice up to Routine.
118
119 min_workers => INT
120 max_workers => INT
121 The lower and upper bounds of worker processes to try to keep running.
122 The actual number running at any time will be kept somewhere between
123 these bounds according to load.
124
125 max_worker_calls => INT
126 Optional. If provided, stop a worker process after it has processed
127 this number of calls. (New workers may be started to replace stopped
128 ones, within the bounds given above).
129
130 idle_timeout => NUM
131 Optional. If provided, idle worker processes will be shut down after
132 this amount of time, if there are more than "min_workers" of them.
133
134 exit_on_die => BOOL
135 Optional boolean, controls what happens after the "code" throws an
136 exception. If missing or false, the worker will continue running to
137 process more requests. If true, the worker will be shut down. A new
138 worker might be constructed by the "call" method to replace it, if
139 necessary.
140
141 setup => ARRAY
142 Optional array reference. Specifies the "setup" key to pass to the
143 underlying IO::Async::Process when setting up new worker processes.
144
146 The following methods documented with a trailing call to "->get" return
147 Future instances.
148
149 start
150 $function->start
151
152 Start the worker processes
153
154 stop
155 $function->stop
156
157 Stop the worker processes
158
159 $f = $function->stop
160
161 Since version 0.75.
162
163 If called in non-void context, returns a IO::Async::Future instance
164 that will complete once every worker process has stopped and exited.
165 This may be useful for waiting until all of the processes are waited
166 on, or other edge-cases, but is not otherwise particularly useful.
167
168 restart
169 $function->restart
170
171 Gracefully stop and restart all the worker processes.
172
173 call
174 @result = $function->call( %params )->get
175
176 Schedules an invocation of the contained function to be executed on one
177 of the worker processes. If a non-busy worker is available now, it will
178 be called immediately. If not, it will be queued and sent to the next
179 free worker that becomes available.
180
181 The request will already have been serialised by the marshaller, so it
182 will be safe to modify any referenced data structures in the arguments
183 after this call returns.
184
185 The %params hash takes the following keys:
186
187 args => ARRAY
188 A reference to the array of arguments to pass to the code.
189
190 priority => NUM
191 Optional. Defines the sorting order when no workers are
192 available and calls must be queued for later. A default of zero
193 will apply if not provided.
194
195 Higher values cause the call to be considered more important,
196 and will be placed earlier in the queue than calls with a
197 smaller value. Calls of equal priority are still handled in
198 FIFO order.
199
200 If the function body returns normally the list of results are provided
201 as the (successful) result of returned future. If the function throws
202 an exception this results in a failed future. In the special case that
203 the exception is in fact an unblessed "ARRAY" reference, this array is
204 unpacked and used as-is for the "fail" result. If the exception is not
205 such a reference, it is used as the first argument to "fail", in the
206 category of "error".
207
208 $f->done( @result )
209
210 $f->fail( @{ $exception } )
211 $f->fail( $exception, error => )
212
213 call (void)
214 $function->call( %params )
215
216 When not returning a future, the "on_result", "on_return" and
217 "on_error" arguments give continuations to handle successful results or
218 failure.
219
220 on_result => CODE
221 A continuation that is invoked when the code has been executed.
222 If the code returned normally, it is called as:
223
224 $on_result->( 'return', @values )
225
226 If the code threw an exception, or some other error occurred
227 such as a closed connection or the process died, it is called
228 as:
229
230 $on_result->( 'error', $exception_name )
231
232 on_return => CODE and on_error => CODE
233 An alternative to "on_result". Two continuations to use in
234 either of the circumstances given above. They will be called
235 directly, without the leading 'return' or 'error' value.
236
237 workers
238 $count = $function->workers
239
240 Returns the total number of worker processes available
241
242 workers_busy
243 $count = $function->workers_busy
244
245 Returns the number of worker processes that are currently busy
246
247 workers_idle
248 $count = $function->workers_idle
249
250 Returns the number of worker processes that are currently idle
251
253 Extended Error Information on Failure
254 The array-unpacking form of exception indiciation allows the function
255 body to more precicely control the resulting failure from the "call"
256 future.
257
258 my $divider = IO::Async::Function->new(
259 code => sub {
260 my ( $numerator, $divisor ) = @_;
261 $divisor == 0 and
262 die [ "Cannot divide by zero", div_zero => $numerator, $divisor ];
263
264 return $numerator / $divisor;
265 }
266 );
267
269 For the record, 123454321 is 11111 * 11111, a square number, and
270 therefore not prime.
271
273 Paul Evans <leonerd@leonerd.org.uk>
274
275
276
277perl v5.36.0 2022-05-31 IO::Async::Function(3)