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 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
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 $f = $function->stop
137
138 Since version 0.75.
139
140 If called in non-void context, returns a IO::Async::Future instance
141 that will complete once every worker process has stopped and exited.
142 This may be useful for waiting until all of the processes are waited
143 on, or other edge-cases, but is not otherwise particularly useful.
144
145 restart
146 $function->restart
147
148 Gracefully stop and restart all the worker processes.
149
150 call
151 @result = $function->call( %params )->get
152
153 Schedules an invocation of the contained function to be executed on one
154 of the worker processes. If a non-busy worker is available now, it will
155 be called immediately. If not, it will be queued and sent to the next
156 free worker that becomes available.
157
158 The request will already have been serialised by the marshaller, so it
159 will be safe to modify any referenced data structures in the arguments
160 after this call returns.
161
162 The %params hash takes the following keys:
163
164 args => ARRAY
165 A reference to the array of arguments to pass to the code.
166
167 priority => NUM
168 Optional. Defines the sorting order when no workers are
169 available and calls must be queued for later. A default of zero
170 will apply if not provided.
171
172 Higher values cause the call to be considered more important,
173 and will be placed earlier in the queue than calls with a
174 smaller value. Calls of equal priority are still handled in
175 FIFO order.
176
177 If the function body returns normally the list of results are provided
178 as the (successful) result of returned future. If the function throws
179 an exception this results in a failed future. In the special case that
180 the exception is in fact an unblessed "ARRAY" reference, this array is
181 unpacked and used as-is for the "fail" result. If the exception is not
182 such a reference, it is used as the first argument to "fail", in the
183 category of "error".
184
185 $f->done( @result )
186
187 $f->fail( @{ $exception } )
188 $f->fail( $exception, error => )
189
190 call (void)
191 $function->call( %params )
192
193 When not returning a future, the "on_result", "on_return" and
194 "on_error" arguments give continuations to handle successful results or
195 failure.
196
197 on_result => CODE
198 A continuation that is invoked when the code has been executed.
199 If the code returned normally, it is called as:
200
201 $on_result->( 'return', @values )
202
203 If the code threw an exception, or some other error occurred
204 such as a closed connection or the process died, it is called
205 as:
206
207 $on_result->( 'error', $exception_name )
208
209 on_return => CODE and on_error => CODE
210 An alternative to "on_result". Two continuations to use in
211 either of the circumstances given above. They will be called
212 directly, without the leading 'return' or 'error' value.
213
214 workers
215 $count = $function->workers
216
217 Returns the total number of worker processes available
218
219 workers_busy
220 $count = $function->workers_busy
221
222 Returns the number of worker processes that are currently busy
223
224 workers_idle
225 $count = $function->workers_idle
226
227 Returns the number of worker processes that are currently idle
228
230 Extended Error Information on Failure
231 The array-unpacking form of exception indiciation allows the function
232 body to more precicely control the resulting failure from the "call"
233 future.
234
235 my $divider = IO::Async::Function->new(
236 code => sub {
237 my ( $numerator, $divisor ) = @_;
238 $divisor == 0 and
239 die [ "Cannot divide by zero", div_zero => $numerator, $divisor ];
240
241 return $numerator / $divisor;
242 }
243 );
244
246 For the record, 123454321 is 11111 * 11111, a square number, and
247 therefore not prime.
248
250 Paul Evans <leonerd@leonerd.org.uk>
251
252
253
254perl v5.30.1 2020-01-30 IO::Async::Function(3)