ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-Fork-Pool/Pool.pm
(Generate patch)

Comparing AnyEvent-Fork-Pool/Pool.pm (file contents):
Revision 1.2 by root, Thu Apr 18 21:37:27 2013 UTC vs.
Revision 1.8 by root, Sun Apr 21 12:28:34 2013 UTC

1=head1 NAME 1=head1 NAME
2 2
3AnyEvent::Fork::Pool - simple process pool manager on top of AnyEvent::Fork 3AnyEvent::Fork::Pool - simple process pool manager on top of AnyEvent::Fork
4
5THE API IS NOT FINISHED, CONSIDER THIS AN ALPHA RELEASE
4 6
5=head1 SYNOPSIS 7=head1 SYNOPSIS
6 8
7 use AnyEvent; 9 use AnyEvent;
8 use AnyEvent::Fork::Pool; 10 use AnyEvent::Fork::Pool;
9 # use AnyEvent::Fork is not needed 11 # use AnyEvent::Fork is not needed
10 12
11 # all parameters with default values 13 # all possible parameters shown, with default values
12 my $pool = new AnyEvent::Fork::Pool 14 my $pool = AnyEvent::Fork
13 "MyWorker::run", 15 ->new
16 ->require ("MyWorker")
17 ->AnyEvent::Fork::Pool::run (
18 "MyWorker::run", # the worker function
14 19
15 # pool management 20 # pool management
16 min => 0, # minimum # of processes
17 max => 4, # maximum # of processes 21 max => 4, # absolute maximum # of processes
18 max_queue => 2, # queue at most this number of jobs per process 22 idle => 0, # minimum # of idle processes
23 load => 2, # queue at most this number of jobs per process
19 min_delay => 0, # wait this many seconds before starting a new process 24 start => 0.1, # wait this many seconds before starting a new process
20 min_idle => 0, # try to have at least this amount of idle processes
21 max_idle => 1, # at most this many idle processes
22 idle_time => 1, # wait this many seconds before killing an idle process 25 stop => 10, # wait this many seconds before stopping an idle process
23 on_destroy => (my $finish = AE::cv), 26 on_destroy => (my $finish = AE::cv), # called when object is destroyed
24 27
25 # template process
26 template => AnyEvent::Fork->new, # the template process to use
27 require => [MyWorker::], # module(s) to load
28 eval => "# perl code to execute in template",
29
30 # parameters passed to AnyEvent::Fork::RPC 28 # parameters passed to AnyEvent::Fork::RPC
31 async => 0, 29 async => 0,
32 on_error => sub { die "FATAL: $_[0]\n" }, 30 on_error => sub { die "FATAL: $_[0]\n" },
33 on_event => sub { my @ev = @_ }, 31 on_event => sub { my @ev = @_ },
34 init => "MyWorker::init", 32 init => "MyWorker::init",
35 serialiser => $AnyEvent::Fork::RPC::STRING_SERIALISER, 33 serialiser => $AnyEvent::Fork::RPC::STRING_SERIALISER,
36 ; 34 );
37 35
38 for (1..10) { 36 for (1..10) {
39 $pool->call (doit => $_, sub { 37 $pool->(doit => $_, sub {
40 print "MyWorker::run returned @_\n"; 38 print "MyWorker::run returned @_\n";
41 }); 39 });
42 } 40 }
43 41
44 undef $pool; 42 undef $pool;
52pool of processes that handles jobs. 50pool of processes that handles jobs.
53 51
54Understanding of L<AnyEvent::Fork> is helpful but not critical to be able 52Understanding of L<AnyEvent::Fork> is helpful but not critical to be able
55to use this module, but a thorough understanding of L<AnyEvent::Fork::RPC> 53to use this module, but a thorough understanding of L<AnyEvent::Fork::RPC>
56is, as it defines the actual API that needs to be implemented in the 54is, as it defines the actual API that needs to be implemented in the
57children. 55worker processes.
58 56
59=head1 EXAMPLES 57=head1 EXAMPLES
60 58
61=head1 PARENT USAGE 59=head1 PARENT USAGE
62 60
61To create a pool, you first have to create a L<AnyEvent::Fork> object -
62this object becomes your template process. Whenever a new worker process
63is needed, it is forked from this template process. Then you need to
64"hand off" this template process to the C<AnyEvent::Fork::Pool> module by
65calling its run method on it:
66
67 my $template = AnyEvent::Fork
68 ->new
69 ->require ("SomeModule", "MyWorkerModule");
70
71 my $pool = $template->AnyEvent::Fork::Pool::run ("MyWorkerModule::myfunction");
72
73The pool "object" is not a regular Perl object, but a code reference that
74you can call and that works roughly like calling the worker function
75directly, except that it returns nothing but instead you need to specify a
76callback to be invoked once results are in:
77
78 $pool->(1, 2, 3, sub { warn "myfunction(1,2,3) returned @_" });
79
63=over 4 80=over 4
64 81
65=cut 82=cut
66 83
67package AnyEvent::Fork::Pool; 84package AnyEvent::Fork::Pool;
68 85
69use common::sense; 86use common::sense;
70 87
71use Scalar::Util (); 88use Scalar::Util ();
72 89
90use Guard ();
73use Array::Heap (); 91use Array::Heap ();
74 92
75use AnyEvent; 93use AnyEvent;
76use AnyEvent::Fork; # we don't actually depend on it, this is for convenience 94use AnyEvent::Fork; # we don't actually depend on it, this is for convenience
77use AnyEvent::Fork::RPC; 95use AnyEvent::Fork::RPC;
78 96
97# these are used for the first and last argument of events
98# in the hope of not colliding. yes, I don't like it either,
99# but didn't come up with an obviously better alternative.
79my $magic0 = ':t6Z@HK1N%Dx@_7?=~-7NQgWDdAs6a,jFN=wLO0*jD*1%P'; 100my $magic0 = ':t6Z@HK1N%Dx@_7?=~-7NQgWDdAs6a,jFN=wLO0*jD*1%P';
80my $magic2 = '<~53rexz.U`!]X[A235^"fyEoiTF\T~oH1l/N6+Djep9b~bI9`\1x%B~vWO1q*'; 101my $magic1 = '<~53rexz.U`!]X[A235^"fyEoiTF\T~oH1l/N6+Djep9b~bI9`\1x%B~vWO1q*';
81 102
82our $VERSION = 0.1; 103our $VERSION = 0.1;
83 104
84=item my $rpc = new AnyEvent::Fork::Pool $function, [key => value...] 105=item my $pool = AnyEvent::Fork::Pool::run $fork, $function, [key => value...]
106
107The traditional way to call the pool creation function. But it is way
108cooler to call it in the following way:
109
110=item my $pool = $fork->AnyEvent::Fork::Pool::run ($function, [key => value...])
85 111
86Creates a new pool object with the specified C<$function> as function 112Creates a new pool object with the specified C<$function> as function
87(name) to call for each request. 113(name) to call for each request. The pool uses the C<$fork> object as the
88 114template when creating worker processes.
89A pool consists of a template process that contains the code and data that
90the worker processes need. And a number of worker processes that have been
91forked off of that template process.
92 115
93You can supply your own template process, or tell C<AnyEvent::Fork::Pool> 116You can supply your own template process, or tell C<AnyEvent::Fork::Pool>
94to create one. 117to create one.
95 118
96A relatively large number of key/value pairs can be specified to influence 119A relatively large number of key/value pairs can be specified to influence
101 124
102=item Pool Management 125=item Pool Management
103 126
104The pool consists of a certain number of worker processes. These options 127The pool consists of a certain number of worker processes. These options
105decide how many of these processes exist and when they are started and 128decide how many of these processes exist and when they are started and
106stopp.ed 129stopped.
130
131The worker pool is dynamically resized, according to (perceived :)
132load. The minimum size is given by the C<idle> parameter and the maximum
133size is given by the C<max> parameter. A new worker is started every
134C<start> seconds at most, and an idle worker is stopped at most every
135C<stop> second.
136
137You can specify the amount of jobs sent to a worker concurrently using the
138C<load> parameter.
107 139
108=over 4 140=over 4
109 141
110=item min => $count (default: 0) 142=item idle => $count (default: 0)
111 143
112The minimum number of processes in the pool, in addition to the template 144The minimum amount of idle processes in the pool - when there are fewer
113process. Even when idle, there will never be fewer than this number of 145than this many idle workers, C<AnyEvent::Fork::Pool> will try to start new
114worker processes. The default means that the pool can be empty. 146ones, subject to the limits set by C<max> and C<start>.
147
148This is also the initial amount of workers in the pool. The default of
149zero means that the pool starts empty and can shrink back to zero workers
150over time.
115 151
116=item max => $count (default: 4) 152=item max => $count (default: 4)
117 153
118The maximum number of processes in the pool, in addition to the template 154The maximum number of processes in the pool, in addition to the template
119process. C<AnyEvent::Fork::Pool> will never create more than this number 155process. C<AnyEvent::Fork::Pool> will never have more than this number of
120of processes. 156worker processes, although there can be more temporarily when a worker is
157shut down and hasn't exited yet.
121 158
122=item max_queue => $count (default: 2) 159=item load => $count (default: 2)
123 160
124The maximum number of jobs sent to a single worker process. Worker 161The maximum number of concurrent jobs sent to a single worker process.
125processes that handle this number of jobs already are called "busy".
126 162
127Jobs that cannot be sent to a worker immediately (because all workers are 163Jobs that cannot be sent to a worker immediately (because all workers are
128busy) will be queued until a worker is available. 164busy) will be queued until a worker is available.
129 165
166Setting this low improves latency. For example, at C<1>, every job that
167is sent to a worker is sent to a completely idle worker that doesn't run
168any other jobs. The downside is that throughput is reduced - a worker that
169finishes a job needs to wait for a new job from the parent.
170
171The default of C<2> is usually a good compromise.
172
130=item min_delay => $seconds (default: 0) 173=item start => $seconds (default: 0.1)
131 174
132When a job is queued and all workers are busy, a timer is started. If the 175When there are fewer than C<idle> workers (or all workers are completely
133timer elapses and there are still jobs that cannot be queued to a worker, 176busy), then a timer is started. If the timer elapses and there are still
134a new worker is started. 177jobs that cannot be queued to a worker, a new worker is started.
135 178
136This configurs the time that all workers must be busy before a new worker 179This sets the minimum time that all workers must be busy before a new
137is started. Or, put differently, the minimum delay betwene starting new 180worker is started. Or, put differently, the minimum delay between starting
138workers. 181new workers.
139 182
140The delay is zero by default, which means new workers will be started 183The delay is small by default, which means new workers will be started
141without delay. 184relatively quickly. A delay of C<0> is possible, and ensures that the pool
185will grow as quickly as possible under load.
142 186
143=item min_idle => $count (default: 0) 187Non-zero values are useful to avoid "exploding" a pool because a lot of
188jobs are queued in an instant.
144 189
145The minimum number of idle workers - when they are less, more 190Higher values are often useful to improve efficiency at the cost of
146are started. The C<min_delay> is still respected though, and 191latency - when fewer processes can do the job over time, starting more and
147C<min_idle>/C<min_delay> and C<max_idle>/C<idle_time> are useful to 192more is not necessarily going to help.
148dynamically adjust the pool.
149 193
150=item max_idle => $count (default: 1)
151
152The maximum number of idle workers. If a worker becomes idle and there are
153already this many idle workers, it will be stopped immediately instead of
154waiting for the idle timer to elapse.
155
156=item idle_time => $seconds (default: 1) 194=item stop => $seconds (default: 10)
157 195
158When a worker has no jobs to execute it becomes idle. An idle worker that 196When a worker has no jobs to execute it becomes idle. An idle worker that
159hasn't executed a job within this amount of time will be stopped, unless 197hasn't executed a job within this amount of time will be stopped, unless
160the other parameters say otherwise. 198the other parameters say otherwise.
161 199
200Setting this to a very high value means that workers stay around longer,
201even when they have nothing to do, which can be good as they don't have to
202be started on the netx load spike again.
203
204Setting this to a lower value can be useful to avoid memory or simply
205process table wastage.
206
207Usually, setting this to a time longer than the time between load spikes
208is best - if you expect a lot of requests every minute and little work
209in between, setting this to longer than a minute avoids having to stop
210and start workers. On the other hand, you have to ask yourself if letting
211workers run idle is a good use of your resources. Try to find a good
212balance between resource usage of your workers and the time to start new
213workers - the processes created by L<AnyEvent::Fork> itself is fats at
214creating workers while not using much memory for them, so most of the
215overhead is likely from your own code.
216
162=item on_destroy => $callback->() (default: none) 217=item on_destroy => $callback->() (default: none)
163 218
164When a pool object goes out of scope, it will still handle all outstanding 219When a pool object goes out of scope, the outstanding requests are still
165jobs. After that, it will destroy all workers (and also the template 220handled till completion. Only after handling all jobs will the workers
166process if it isn't referenced otherwise). 221be destroyed (and also the template process if it isn't referenced
222otherwise).
223
224To find out when a pool I<really> has finished its work, you can set this
225callback, which will be called when the pool has been destroyed.
167 226
168=back 227=back
169 228
170=item Template Process 229=item AnyEvent::Fork::RPC Parameters
171 230
172The worker processes are all forked from a single template 231These parameters are all passed more or less directly to
173process. Ideally, all modules and all cdoe used by the worker, as well as 232L<AnyEvent::Fork::RPC>. They are only briefly mentioned here, for
174any shared data structures should be loaded into the template process, to 233their full documentation please refer to the L<AnyEvent::Fork::RPC>
175take advantage of data sharing via fork. 234documentation. Also, the default values mentioned here are only documented
176 235as a best effort - the L<AnyEvent::Fork::RPC> documentation is binding.
177You can create your own template process by creating a L<AnyEvent::Fork>
178object yourself and passing it as the C<template> parameter, but
179C<AnyEvent::Fork::Pool> can create one for you, including some standard
180options.
181 236
182=over 4 237=over 4
183 238
184=item template => $fork (default: C<< AnyEvent::Fork->new >>) 239=item async => $boolean (default: 0)
185 240
186The template process to use, if you want to create your own. 241Whether to use the synchronous or asynchronous RPC backend.
187 242
188=item require => \@modules (default: C<[]>) 243=item on_error => $callback->($message) (default: die with message)
189 244
190The modules in this list will be laoded into the template process. 245The callback to call on any (fatal) errors.
191 246
192=item eval => "# perl code to execute in template" (default: none) 247=item on_event => $callback->(...) (default: C<sub { }>, unlike L<AnyEvent::Fork::RPC>)
193 248
194This is a perl string that is evaluated after creating the template 249The callback to invoke on events.
195process and after requiring the modules. It can do whatever it wants to 250
196configure the process, but it must not do anything that would keep a later 251=item init => $initfunction (default: none)
197fork from working (so must not create event handlers or (real) threads for 252
198example). 253The function to call in the child, once before handling requests.
254
255=item serialiser => $serialiser (defailt: $AnyEvent::Fork::RPC::STRING_SERIALISER)
256
257The serialiser to use.
199 258
200=back 259=back
201 260
202=item AnyEvent::Fork::RPC Parameters
203
204These parameters are all passed directly to L<AnyEvent::Fork::RPC>. They
205are only briefly mentioned here, for their full documentation
206please refer to the L<AnyEvent::Fork::RPC> documentation. Also, the
207default values mentioned here are only documented as a best effort -
208L<AnyEvent::Fork::RPC> documentation is binding.
209
210=over 4
211
212=item async => $boolean (default: 0)
213
214Whether to sue the synchronous or asynchronous RPC backend.
215
216=item on_error => $callback->($message) (default: die with message)
217
218The callback to call on any (fatal) errors.
219
220=item on_event => $callback->(...) (default: C<sub { }>, unlike L<AnyEvent::Fork::RPC>)
221
222The callback to invoke on events.
223
224=item init => $initfunction (default: none)
225
226The function to call in the child, once before handling requests.
227
228=item serialiser => $serialiser (defailt: $AnyEvent::Fork::RPC::STRING_SERIALISER)
229
230The serialiser to use.
231
232=back 261=back
233 262
234=back
235
236=cut 263=cut
237 264
238sub new { 265sub run {
239 my ($class, $function, %arg) = @_; 266 my ($template, $function, %arg) = @_;
240 267
241 my $self = bless { 268 my $max = $arg{max} || 4;
242 min => 0, 269 my $idle = $arg{idle} || 0,
243 max => 4, 270 my $load = $arg{load} || 2,
244 max_queue => 2, 271 my $start = $arg{start} || 0.1,
245 min_delay => 0, 272 my $stop = $arg{stop} || 10,
246 max_idle => 1, 273 my $on_event = $arg{on_event} || sub { },
247 idle_time => 1, 274 my $on_destroy = $arg{on_destroy};
248 on_event => sub { },
249 %arg,
250 pool => [],
251 queue => [],
252 }, $class;
253 275
254 $self->{function} = $function; 276 my @rpc = (
277 async => $arg{async},
278 init => $arg{init},
279 serialiser => delete $arg{serialiser},
280 on_error => $arg{on_error},
281 );
255 282
256 ($self->{template} ||= new AnyEvent::Fork) 283 my (@pool, @queue, $nidle, $start_w, $stop_w, $shutdown);
284 my ($start_worker, $stop_worker, $want_start, $want_stop, $scheduler);
285
286 my $destroy_guard = Guard::guard {
287 $on_destroy->()
288 if $on_destroy;
289 };
290
291 $template
257 ->require ("AnyEvent::Fork::RPC::" . ($self->{async} ? "Async" : "Sync")) 292 ->require ("AnyEvent::Fork::RPC::" . ($arg{async} ? "Async" : "Sync"))
258 ->require (@{ delete $self->{require} })
259 ->eval (' 293 ->eval ('
260 my ($magic0, $magic2) = @_; 294 my ($magic0, $magic1) = @_;
261 sub AnyEvent::Fork::Pool::quit() { 295 sub AnyEvent::Fork::Pool::retire() {
262 AnyEvent::Fork::RPC::on_event $magic0, "quit", $magic2; 296 AnyEvent::Fork::RPC::event $magic0, "quit", $magic1;
263 } 297 }
264 ', $magic0, $magic2) 298 ', $magic0, $magic1)
265 ->eval (delete $self->{eval}); 299 ;
266 300
267 $self->start 301 $start_worker = sub {
268 while @{ $self->{pool} } < $self->{min}; 302 my $proc = [0, 0, undef]; # load, index, rpc
269 303
270 $self 304 $proc->[2] = $template
305 ->fork
306 ->AnyEvent::Fork::RPC::run ($function,
307 @rpc,
308 on_event => sub {
309 if (@_ == 3 && $_[0] eq $magic0 && $_[2] eq $magic1) {
310 $destroy_guard if 0; # keep it alive
311
312 $_[1] eq "quit" and $stop_worker->($proc);
313 return;
314 }
315
316 &$on_event;
317 },
318 )
319 ;
320
321 ++$nidle;
322 Array::Heap::push_heap_idx @pool, $proc;
323
324 Scalar::Util::weaken $proc;
325 };
326
327 $stop_worker = sub {
328 my $proc = shift;
329
330 $proc->[0]
331 or --$nidle;
332
333 Array::Heap::splice_heap_idx @pool, $proc->[1]
334 if defined $proc->[1];
335
336 @$proc = 0; # tell others to leave it be
337 };
338
339 $want_start = sub {
340 undef $stop_w;
341
342 $start_w ||= AE::timer $start, $start, sub {
343 if (($nidle < $idle || @queue) && @pool < $max) {
344 $start_worker->();
345 $scheduler->();
346 } else {
347 undef $start_w;
348 }
349 };
350 };
351
352 $want_stop = sub {
353 $stop_w ||= AE::timer $stop, $stop, sub {
354 $stop_worker->($pool[0])
355 if $nidle;
356
357 undef $stop_w
358 if $nidle <= $idle;
359 };
360 };
361
362 $scheduler = sub {
363 if (@queue) {
364 while (@queue) {
365 @pool or $start_worker->();
366
367 my $proc = $pool[0];
368
369 if ($proc->[0] < $load) {
370 # found free worker, increase load
371 unless ($proc->[0]++) {
372 # worker became busy
373 --$nidle
374 or undef $stop_w;
375
376 $want_start->()
377 if $nidle < $idle && @pool < $max;
378 }
379
380 Array::Heap::adjust_heap_idx @pool, 0;
381
382 my $job = shift @queue;
383 my $ocb = pop @$job;
384
385 $proc->[2]->(@$job, sub {
386 # reduce load
387 --$proc->[0] # worker still busy?
388 or ++$nidle > $idle # not too many idle processes?
389 or $want_stop->();
390
391 Array::Heap::adjust_heap_idx @pool, $proc->[1]
392 if defined $proc->[1];
393
394 &$ocb;
395
396 $scheduler->();
397 });
398 } else {
399 $want_start->()
400 unless @pool >= $max;
401
402 last;
403 }
404 }
405 } elsif ($shutdown) {
406 @pool = ();
407 undef $start_w;
408 undef $start_worker; # frees $destroy_guard reference
409
410 $stop_worker->($pool[0])
411 while $nidle;
412 }
413 };
414
415 my $shutdown_guard = Guard::guard {
416 $shutdown = 1;
417 $scheduler->();
418 };
419
420 $start_worker->()
421 while @pool < $idle;
422
423 sub {
424 $shutdown_guard if 0; # keep it alive
425
426 $start_worker->()
427 unless @pool;
428
429 push @queue, [@_];
430 $scheduler->();
431 }
271} 432}
272 433
273sub start {
274 my ($self) = @_;
275
276 warn "start\n";#d#
277
278 Scalar::Util::weaken $self;
279
280 my $proc = [0, undef, undef];
281
282 $proc->[1] = $self->{template}
283 ->fork
284 ->AnyEvent::Fork::RPC::run ($self->{function},
285 async => $self->{async},
286 init => $self->{init},
287 serialiser => $self->{serialiser},
288 on_error => $self->{on_error},
289 on_event => sub {
290 if (@_ == 3 && $_[0] eq $magic0 && $_[2] eq $magic2) {
291 if ($_[1] eq "quit") {
292 my $pool = $self->{pool};
293 for (0 .. $#$pool) {
294 if ($pool->[$_] == $proc) {
295 Array::Heap::splice_heap @$pool, $_;
296 return;
297 }
298 }
299 die;
300 }
301 return;
302 }
303
304 &{ $self->{on_event} };
305 },
306 )
307 ;
308
309 ++$self->{idle};
310 Array::Heap::push_heap @{ $self->{pool} }, $proc;
311}
312
313=item $pool->call (..., $cb->(...)) 434=item $pool->(..., $cb->(...))
314 435
315Call the RPC function of a worker with the given arguments, and when the 436Call the RPC function of a worker with the given arguments, and when the
316worker is done, call the C<$cb> with the results, like just calling the 437worker is done, call the C<$cb> with the results, just like calling the
317L<AnyEvent::Fork::RPC> object directly. 438RPC object durectly - see the L<AnyEvent::Fork::RPC> documentation for
439details on the RPC API.
318 440
319If there is no free worker, the call will be queued. 441If there is no free worker, the call will be queued until a worker becomes
442available.
320 443
321Note that there can be considerable time between calling this method and 444Note that there can be considerable time between calling this method and
322the call actually being executed. During this time, the parameters passed 445the call actually being executed. During this time, the parameters passed
323to this function are effectively read-only - modifying them after the call 446to this function are effectively read-only - modifying them after the call
324and before the callback is invoked causes undefined behaviour. 447and before the callback is invoked causes undefined behaviour.
325 448
326=cut 449=cut
327 450
328sub scheduler {
329 my $self = shift;
330
331 my $pool = $self->{pool};
332 my $queue = $self->{queue};
333
334 $self->start
335 unless @$pool;
336
337 while (@$queue) {
338 my $proc = $pool->[0];
339
340 if ($proc->[0] < $self->{max_queue}) {
341 warn "free $proc $proc->[0]\n";#d#
342 # found free worker
343 --$self->{idle}
344 unless $proc->[0]++;
345
346 undef $proc->[2];
347
348 Array::Heap::adjust_heap @$pool, 0;
349
350 my $job = shift @$queue;
351 my $ocb = pop @$job;
352
353 $proc->[1]->(@$job, sub {
354 for (0 .. $#$pool) {
355 if ($pool->[$_] == $proc) {
356 # reduce queue counter
357 unless (--$pool->[$_][0]) {
358 # worker becomes idle
359 my $to = ++$self->{idle} > $self->{max_idle}
360 ? 0
361 : $self->{idle_time};
362
363 $proc->[2] = AE::timer $to, 0, sub {
364 undef $proc->[2];
365
366 warn "destroy $proc afzer $to\n";#d#
367
368 for (0 .. $#$pool) {
369 if ($pool->[$_] == $proc) {
370 Array::Heap::splice_heap @$pool, $_;
371 --$self->{idle};
372 last;
373 }
374 }
375 };
376 }
377
378 Array::Heap::adjust_heap @$pool, $_;
379 last;
380 }
381 }
382 &$ocb;
383 });
384 } else {
385 warn "busy $proc->[0]\n";#d#
386 # all busy, delay
387
388 $self->{min_delay_w} ||= AE::timer $self->{min_delay}, 0, sub {
389 delete $self->{min_delay_w};
390
391 if (@{ $self->{queue} }) {
392 $self->start;
393 $self->scheduler;
394 }
395 };
396 last;
397 }
398 }
399 warn "last\n";#d#
400}
401
402sub call {
403 my $self = shift;
404
405 push @{ $self->{queue} }, [@_];
406 $self->scheduler;
407}
408
409sub DESTROY {
410 $_[0]{on_destroy}->();
411}
412
413=back 451=back
452
453=head1 CHILD USAGE
454
455In addition to the L<AnyEvent::Fork::RPC> API, this module implements one
456more child-side function:
457
458=over 4
459
460=item AnyEvent::Fork::Pool::retire ()
461
462This function sends an event to the parent process to request retirement:
463the worker is removed from the pool and no new jobs will be sent to it,
464but it has to handle the jobs that are already queued.
465
466The parentheses are part of the syntax: the function usually isn't defined
467when you compile your code (because that happens I<before> handing the
468template process over to C<AnyEvent::Fork::Pool::run>, so you need the
469empty parentheses to tell Perl that the function is indeed a function.
470
471Retiring a worker can be useful to gracefully shut it down when the worker
472deems this useful. For example, after executing a job, one could check
473the process size or the number of jobs handled so far, and if either is
474too high, the worker could ask to get retired, to avoid memory leaks to
475accumulate.
476
477=back
478
479=head1 POOL PARAMETERS RECIPES
480
481This section describes some recipes for pool paramaters. These are mostly
482meant for the synchronous RPC backend, as the asynchronous RPC backend
483changes the rules considerably, making workers themselves responsible for
484their scheduling.
485
486=over 4
487
488=item low latency - set load = 1
489
490If you need a deterministic low latency, you should set the C<load>
491parameter to C<1>. This ensures that never more than one job is sent to
492each worker. This avoids having to wait for a previous job to finish.
493
494This makes most sense with the synchronous (default) backend, as the
495asynchronous backend can handle multiple requests concurrently.
496
497=item lowest latency - set load = 1 and idle = max
498
499To achieve the lowest latency, you additionally should disable any dynamic
500resizing of the pool by setting C<idle> to the same value as C<max>.
501
502=item high throughput, cpu bound jobs - set load >= 2, max = #cpus
503
504To get high throughput with cpu-bound jobs, you should set the maximum
505pool size to the number of cpus in your system, and C<load> to at least
506C<2>, to make sure there can be another job waiting for the worker when it
507has finished one.
508
509The value of C<2> for C<load> is the minimum value that I<can> achieve
510100% throughput, but if your parent process itself is sometimes busy, you
511might need higher values. Also there is a limit on the amount of data that
512can be "in flight" to the worker, so if you send big blobs of data to your
513worker, C<load> might have much less of an effect.
514
515=item high throughput, I/O bound jobs - set load >= 2, max = 1, or very high
516
517When your jobs are I/O bound, using more workers usually boils down to
518higher throughput, depending very much on your actual workload - sometimes
519having only one worker is best, for example, when you read or write big
520files at maixmum speed, as a second worker will increase seek times.
521
522=back
523
524=head1 EXCEPTIONS
525
526The same "policy" as with L<AnyEvent::Fork::RPC> applies - exceptins will
527not be caught, and exceptions in both worker and in callbacks causes
528undesirable or undefined behaviour.
414 529
415=head1 SEE ALSO 530=head1 SEE ALSO
416 531
417L<AnyEvent::Fork>, to create the processes in the first place. 532L<AnyEvent::Fork>, to create the processes in the first place.
418 533

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines