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       If the function body returns normally the list of results are provided
159       as the (successful) result of returned future. If the function throws
160       an exception this results in a failed future. In the special case that
161       the exception is in fact an unblessed "ARRAY" reference, this array is
162       unpacked and used as-is for the "fail" result. If the exception is not
163       such a reference, it is used as the first argument to "fail", in the
164       category of "error".
165
166          $f->done( @result )
167
168          $f->fail( @{ $exception } )
169          $f->fail( $exception, error => )
170
171   call (void)
172          $function->call( %params )
173
174       When not returning a future, the "on_result", "on_return" and
175       "on_error" arguments give continuations to handle successful results or
176       failure.
177
178       on_result => CODE
179               A continuation that is invoked when the code has been executed.
180               If the code returned normally, it is called as:
181
182                $on_result->( 'return', @values )
183
184               If the code threw an exception, or some other error occurred
185               such as a closed connection or the process died, it is called
186               as:
187
188                $on_result->( 'error', $exception_name )
189
190       on_return => CODE and on_error => CODE
191               An alternative to "on_result". Two continuations to use in
192               either of the circumstances given above. They will be called
193               directly, without the leading 'return' or 'error' value.
194
195   workers
196          $count = $function->workers
197
198       Returns the total number of worker processes available
199
200   workers_busy
201          $count = $function->workers_busy
202
203       Returns the number of worker processes that are currently busy
204
205   workers_idle
206          $count = $function->workers_idle
207
208       Returns the number of worker processes that are currently idle
209

EXAMPLES

211   Extended Error Information on Failure
212       The array-unpacking form of exception indiciation allows the function
213       body to more precicely control the resulting failure from the "call"
214       future.
215
216        my $divider = IO::Async::Function->new(
217           code => sub {
218              my ( $numerator, $divisor ) = @_;
219              $divisor == 0 and
220                 die [ "Cannot divide by zero", div_zero => $numerator, $divisor ];
221
222              return $numerator / $divisor;
223           }
224        );
225

NOTES

227       For the record, 123454321 is 11111 * 11111, a square number, and
228       therefore not prime.
229

AUTHOR

231       Paul Evans <leonerd@leonerd.org.uk>
232
233
234
235perl v5.28.0                      2018-07-14            IO::Async::Function(3)
Impressum