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

Comparing AnyEvent/lib/AnyEvent.pm (file contents):
Revision 1.104 by root, Wed Apr 30 11:40:22 2008 UTC vs.
Revision 1.105 by root, Thu May 1 12:35:54 2008 UTC

297 # do something else, then wait for process exit 297 # do something else, then wait for process exit
298 $done->wait; 298 $done->wait;
299 299
300=head2 CONDITION VARIABLES 300=head2 CONDITION VARIABLES
301 301
302If you are familiar with some event loops you will know that all of them
303require you to run some blocking "loop", "run" or similar function that
304will actively watch for new events and call your callbacks.
305
306AnyEvent is different, it expects somebody else to run the event loop and
307will only block when necessary (usually when told by the user).
308
309The instrument to do that is called a "condition variable", so called
310because they represent a condition that must become true.
311
302Condition variables can be created by calling the C<< AnyEvent->condvar >> 312Condition variables can be created by calling the C<< AnyEvent->condvar
303method without any arguments. 313>> method, usually without arguments. The only argument pair allowed is
314C<cb>, which specifies a callback to be called when the condition variable
315becomes true.
304 316
305A condition variable waits for a condition - precisely that the C<< 317After creation, the conditon variable is "false" until it becomes "true"
306->broadcast >> method has been called. 318by calling the C<broadcast> method.
307 319
308They are very useful to signal that a condition has been fulfilled, for 320Condition variables are similar to callbacks, except that you can
321optionally wait for them. They can also be called merge points - points
322in time where multiple outstandign events have been processed. And yet
323another way to call them is transations - each condition variable can be
324used to represent a transaction, which finishes at some point and delivers
325a result.
326
327Condition variables are very useful to signal that something has finished,
309example, if you write a module that does asynchronous http requests, 328for example, if you write a module that does asynchronous http requests,
310then a condition variable would be the ideal candidate to signal the 329then a condition variable would be the ideal candidate to signal the
311availability of results. 330availability of results. The user can either act when the callback is
331called or can synchronously C<< ->wait >> for the results.
312 332
313You can also use condition variables to block your main program until 333You can also use them to simulate traditional event loops - for example,
314an event occurs - for example, you could C<< ->wait >> in your main 334you can block your main program until an event occurs - for example, you
315program until the user clicks the Quit button in your app, which would C<< 335could C<< ->wait >> in your main program until the user clicks the Quit
316->broadcast >> the "quit" event. 336button of your app, which would C<< ->broadcast >> the "quit" event.
317 337
318Note that condition variables recurse into the event loop - if you have 338Note that condition variables recurse into the event loop - if you have
319two pirces of code that call C<< ->wait >> in a round-robbin fashion, you 339two pieces of code that call C<< ->wait >> in a round-robbin fashion, you
320lose. Therefore, condition variables are good to export to your caller, but 340lose. Therefore, condition variables are good to export to your caller, but
321you should avoid making a blocking wait yourself, at least in callbacks, 341you should avoid making a blocking wait yourself, at least in callbacks,
322as this asks for trouble. 342as this asks for trouble.
323 343
324This object has two methods: 344Condition variables are represented by hash refs in perl, and the keys
345used by AnyEvent itself are all named C<_ae_XXX> to make subclassing
346easy (it is often useful to build your own transaction class on top of
347AnyEvent). To subclass, use C<AnyEvent::CondVar> as base class and call
348it's C<new> method in your own C<new> method.
325 349
326=over 4 350There are two "sides" to a condition variable - the "producer side" which
327 351eventually calls C<< -> broadcast >>, and the "consumer side", which waits
328=item $cv->wait 352for the broadcast to occur.
329
330Wait (blocking if necessary) until the C<< ->broadcast >> method has been
331called on c<$cv>, while servicing other watchers normally.
332
333You can only wait once on a condition - additional calls will return
334immediately.
335
336Not all event models support a blocking wait - some die in that case
337(programs might want to do that to stay interactive), so I<if you are
338using this from a module, never require a blocking wait>, but let the
339caller decide whether the call will block or not (for example, by coupling
340condition variables with some kind of request results and supporting
341callbacks so the caller knows that getting the result will not block,
342while still suppporting blocking waits if the caller so desires).
343
344Another reason I<never> to C<< ->wait >> in a module is that you cannot
345sensibly have two C<< ->wait >>'s in parallel, as that would require
346multiple interpreters or coroutines/threads, none of which C<AnyEvent>
347can supply (the coroutine-aware backends L<AnyEvent::Impl::CoroEV> and
348L<AnyEvent::Impl::CoroEvent> explicitly support concurrent C<< ->wait >>'s
349from different coroutines, however).
350
351=item $cv->broadcast
352
353Flag the condition as ready - a running C<< ->wait >> and all further
354calls to C<wait> will (eventually) return after this method has been
355called. If nobody is waiting the broadcast will be remembered..
356
357=back
358 353
359Example: 354Example:
360 355
361 # wait till the result is ready 356 # wait till the result is ready
362 my $result_ready = AnyEvent->condvar; 357 my $result_ready = AnyEvent->condvar;
368 my $w = AnyEvent->timer ( 363 my $w = AnyEvent->timer (
369 after => 1, 364 after => 1,
370 cb => sub { $result_ready->broadcast }, 365 cb => sub { $result_ready->broadcast },
371 ); 366 );
372 367
373 # this "blocks" (while handling events) till the watcher 368 # this "blocks" (while handling events) till the callback
374 # calls broadcast 369 # calls broadcast
375 $result_ready->wait; 370 $result_ready->wait;
371
372=head3 METHODS FOR PRODUCERS
373
374These methods should only be used by the producing side, i.e. the
375code/module that eventually broadcasts the signal. Note that it is also
376the producer side which creates the condvar in most cases, but it isn't
377uncommon for the consumer to create it as well.
378
379=over 4
380
381=item $cv->broadcast (...)
382
383Flag the condition as ready - a running C<< ->wait >> and all further
384calls to C<wait> will (eventually) return after this method has been
385called. If nobody is waiting the broadcast will be remembered.
386
387If a callback has been set on the condition variable, it is called
388immediately from within broadcast.
389
390Any arguments passed to the C<broadcast> call will be returned by all
391future C<< ->wait >> calls.
392
393=item $cv->croak ($error)
394
395Similar to broadcast, but causes all call's wait C<< ->wait >> to invoke
396C<Carp::croak> with the given error message/object/scalar.
397
398This can be used to signal any errors to the condition variable
399user/consumer.
400
401=item $cv->begin ([group callback])
402
403=item $cv->end
404
405These two methods can be used to combine many transactions/events into
406one. For example, a function that pings many hosts in parallel might want
407to use a condition variable for the whole process.
408
409Every call to C<< ->begin >> will increment a counter, and every call to
410C<< ->end >> will decrement it. If the counter reaches C<0> in C<< ->end
411>>, the (last) callback passed to C<begin> will be executed. That callback
412is I<supposed> to call C<< ->broadcast >>, but that is not required. If no
413callback was set, C<broadcast> will be called without any arguments.
414
415Let's clarify this with the ping example:
416
417 my $cv = AnyEvent->condvar;
418
419 my %result;
420 $cv->begin (sub { $cv->broadcast (\%result) });
421
422 for my $host (@list_of_hosts) {
423 $cv->begin;
424 ping_host_then_call_callback $host, sub {
425 $result{$host} = ...;
426 $cv->end;
427 };
428 }
429
430 $cv->end;
431
432This code fragment supposedly pings a number of hosts and calls
433C<broadcast> after results for all then have have been gathered - in any
434order. To achieve this, the code issues a call to C<begin> when it starts
435each ping request and calls C<end> when it has received some result for
436it. Since C<begin> and C<end> only maintain a counter, the order in which
437results arrive is not relevant.
438
439There is an additional bracketing call to C<begin> and C<end> outside the
440loop, which serves two important purposes: first, it sets the callback
441to be called once the counter reaches C<0>, and second, it ensures that
442broadcast is called even when C<no> hosts are being pinged (the loop
443doesn't execute once).
444
445This is the general pattern when you "fan out" into multiple subrequests:
446use an outer C<begin>/C<end> pair to set the callback and ensure C<end>
447is called at least once, and then, for each subrequest you start, call
448C<begin> and for eahc subrequest you finish, call C<end>.
449
450=back
451
452=head3 METHODS FOR CONSUMERS
453
454These methods should only be used by the consuming side, i.e. the
455code awaits the condition.
456
457=item $cv->wait
458
459Wait (blocking if necessary) until the C<< ->broadcast >> or C<< ->croak
460>> methods have been called on c<$cv>, while servicing other watchers
461normally.
462
463You can only wait once on a condition - additional calls are valid but
464will return immediately.
465
466If an error condition has been set by calling C<< ->croak >>, then this
467function will call C<croak>.
468
469In list context, all parameters passed to C<broadcast> will be returned,
470in scalar context only the first one will be returned.
471
472Not all event models support a blocking wait - some die in that case
473(programs might want to do that to stay interactive), so I<if you are
474using this from a module, never require a blocking wait>, but let the
475caller decide whether the call will block or not (for example, by coupling
476condition variables with some kind of request results and supporting
477callbacks so the caller knows that getting the result will not block,
478while still suppporting blocking waits if the caller so desires).
479
480Another reason I<never> to C<< ->wait >> in a module is that you cannot
481sensibly have two C<< ->wait >>'s in parallel, as that would require
482multiple interpreters or coroutines/threads, none of which C<AnyEvent>
483can supply (the coroutine-aware backends L<AnyEvent::Impl::CoroEV> and
484L<AnyEvent::Impl::CoroEvent> explicitly support concurrent C<< ->wait >>'s
485from different coroutines, however).
486
487You can ensure that C<< -wait >> never blocks by setting a callback and
488only calling C<< ->wait >> from within that callback (or at a later
489time). This will work even when the event loop does not support blocking
490waits otherwise.
491
492=back
376 493
377=head1 GLOBAL VARIABLES AND FUNCTIONS 494=head1 GLOBAL VARIABLES AND FUNCTIONS
378 495
379=over 4 496=over 4
380 497

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines