Guest User

Untitled

a guest
Jul 23rd, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. use strict;
  2. use warnings;
  3.  
  4.  
  5. use Continuation::Escape;
  6.  
  7. sub timeout {
  8. my ($time, $code, @args) = @_;
  9. my $wantarray = wantarray;
  10.  
  11. print "woot\n";
  12.  
  13. my @res;
  14. my $timed_out = call_cc {
  15. my $escape = shift;
  16.  
  17. local $SIG{'ALRM'} = sub { print "catched\n"; $escape->(1) };
  18. alarm $time;
  19.  
  20. if ( $wantarray ) { @res = $code->( @args ) }
  21. elsif ( defined $wantarray ) { $res[0] = $code->( @args ) }
  22. else { $code->( @args ) }
  23.  
  24. alarm 0;
  25. return 0;
  26. };
  27. die "Exception::Timeout" if $timed_out;
  28.  
  29. return $wantarray? @res : $res[0];
  30. }
  31.  
  32. my $timeout = 3;
  33.  
  34. my @res = eval { timeout( $timeout, \&foo ) };
  35.  
  36. print "$@" if $@;
  37.  
  38. print "success\n";
  39.  
  40. sub foo {
  41. for ( my $i = 0; $i < 100; $i++) {
  42. eval "sleep 1; 1" or print "$@"; print "$i\n";
  43. }
  44. }
Add Comment
Please, Sign In to add comment