Created
January 31, 2012 20:38
-
-
Save wki/1712760 to your computer and use it in GitHub Desktop.
await - defer demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use feature ':5.10'; | |
use AnyEvent; | |
our $await_info; | |
sub on_timeout { | |
my ($timeout, $code) = @_; | |
push @{$await_info->{timers}}, AnyEvent->timer( | |
after => $timeout / 1000, | |
cb => $code, | |
); | |
} | |
sub await(&) { | |
my $code = shift; | |
local $await_info = { | |
timers => [], | |
to_defer => {}, | |
done => AnyEvent->condvar, | |
}; | |
$code->(); | |
$await_info->{done}->send if !%{$await_info->{to_defer}}; | |
$await_info->{done}->recv; | |
} | |
sub defer { | |
my $to_defer = $await_info->{to_defer}; | |
my $id = scalar(keys(%$to_defer)) + 1; | |
$to_defer->{$id} = 1; | |
say " $id defer request"; | |
return sub { | |
say " $id defer done"; | |
delete $to_defer->{$id}; | |
$await_info->{done}->send if !%$to_defer; | |
}; | |
} | |
### testing... | |
say 'starting a 2s wait block'; | |
await { | |
# leave this thing after all timeouts are over | |
on_timeout(1000, defer()); | |
on_timeout(2000, defer()); | |
}; | |
say '2s wait block done'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment