SlideShare una empresa de Scribd logo
1 de 27
Descargar para leer sin conexión
AnyEvent
    Achilles Xu
formalin14@gmail.com
Contents

Hello World

Watcher

CondVar




Bugs
EV, libevent, POE, Glib, QT, Tk
Hello World
use AnyEvent;

my $cv = AnyEvent->condvar;

my $w = AnyEvent->timer(

     'after' => 5,

     'cb' => sub {

         print "hello worldn";

         $cv->send;

     }

);

$cv->recv;
watcher

   I/O

   timer

   signal

   child process

   idle

condvar



   AnyEvent::Handle

   AnyEvent::DNS

   AnyEvent::Socket
I/O Watcher
use AnyEvent;

$| = 1; print "enter your name> ";

my $name;

my $wait_for_input = AnyEvent->io (
   fh   => *STDIN, # which file handle to check
   poll => "r",     # which event to wait for ("r"ead data)
   cb   => sub {    # what callback to execute
      $name = <STDIN>; # read it
   }
);

# do something else here
Timer Watcher

     my $once_per_second = AnyEvent->timer (
      after => 0,    # first invoke ASAP
      interval => 1, # then invoke every second
      cb    => sub { # the callback to invoke
         print "hin";
      },
);
Watcher



Watcher
Watcher
use AnyEvent;

sub aaa {

    my $w = AnyEvent->Timer(

         after => 3,

         interval => 5,

         cb => sub { print "hellon"; }

    );

}

my $cv = AnyEvent->condvar;

aaa();

$cv->recv;      # won't print hello every 5 seconds.
Watcher
use AnyEvent;

my $w;      #   Watcher

sub aaa {

    $w = AnyEvent->Timer(

         after => 3,

         interval => 5,

         cb => sub { print "hellon"; }

    );

}

my $cv = AnyEvent->condvar;

aaa();

$cv->recv;       # will print hello every 5 seconds.
Watcher
use AnyEvent;

sub aaa {

    #           watcher

    my $w; $w = AnyEvent->Timer(

         after => 3,

         interval => 5,

         cb => sub { print "hellon"; $w; }

    );

}

my $cv = AnyEvent->condvar;

aaa();

$cv->recv;      # will print hello every 5 seconds.
Watcher
use AnyEvent;

sub aaa {

    my $w; $w = AnyEvent->timer(

         after => 5,

         cb => sub {

               print "hellon";

               undef $w;

         });

}

aaa();

AnyEvent->condvar()->recv();
CondVar

   main loop       POE::Kernal->run();

               $thread->join();

“This module is an AnyEvent user, you
need to make sure that you use and
run a supported event loop.”
CondVar
use AnyEvent;

my $w = AnyEvent->timer(

     after => 0,

     interval => 5,

     cb => sub {

         print "hellon";

     }

);

my $cv = AnyEvent->condvar;

$cv->recv;      # just like while (1) {...}
CondVar
use AnyEvent;

use AnyEvent::HTTP;

#                 ...

my @cvs;

for (1 .. 5) {

    my $cv = AnyEvent->condvar;          # like thread id

    push @cvs, $cv;

    http_get("http://some_url", sub {

           $cv->send;         # like return in thread func

    });

}

$_->recv for @cvs;        # like $_->join for @threads;

#                       ...
closure

PP   Par::Packer

perl -T
use AnyEvent;

my $x = "Tom";

AnyEvent->timer(afer => 5, cb => sub {

    print "hello $x";

}
use AnyEvent;
use AnyEvent::Handle;
my $cv = AnyEvent->condvar;
my $hdl; $hdl = new AnyEvent::Handle
   fh => *STDIN,
   on_error => sub {
      my ($hdl, $fatal, $msg) = @_;
      warn "got error $msgn";
      $hdl->destroy;
      $cv->send;
   };
# send some request line
$hdl->push_write ("getinfo015012");
# read the response line
$hdl->push_read (line => sub {
    my ($hdl, $line) = @_;
    warn "got line <$line>n";
    $cv->send;
});
$cv->recv;
use AnyEvent;

use AnyEvent::HTTP;

my $cv = AnyEvent->condvar;

http_get("http://www.sina.com.cn",   #      watcher

        sub {

              my ($data, $headers) = @_;

              print $headers->{Status}, "n";

              print $data, "n";

              $cv->send;

        });

$cv->recv;
use AnyEvent; # not AE


  # file handle or descriptor readable
  my $w = AE::io $fh, 0, sub { ... };

  # one-shot or repeating timers
  my $w = AE::timer $seconds,         0, sub { ... }; # once
  my $w = AE::timer $seconds, $interval, sub { ... }; # repeated

  print AE::now; # prints current event loop time
  print AE::time; # think Time::HiRes::time or simply
CORE::time.

  my $cv = AE::cv;
http_get_retry("http://www.sina.com.cn",

    max_retries => 3,

    sub {

          my ($data, $headers) = @_;

          if (defined $data) {

              print "load ok";

          } else {

              print "try 3 times failed";

          }

    });
http_get_file("http://aaa.com/somefile.tar.gz",

    "/data/files/somefile.tar.gz",

    max_concurrent => 20,

    sub {

          my ($data, $headers) = @_;

          if (defined $data) {

              print "download ok";

          } else {

              print "some error happens: " . $headers->{Status};

          }

    });
http_get( $url, sub { ... });

  DNS Resolving

  TCP Connecting

  Sending Request

  Reading Response
Bugs

           socket

accept       push_read

rtimeout

    EV     PurePerl
Bug's Solution


             timer

*AE::now = sub { return AE::time; }

*AE::now = *AE::time doesn't work
Questions?

Más contenido relacionado

La actualidad más candente

Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7
Masahiro Nagano
 
Controlling Arduino With PHP
Controlling Arduino With PHPControlling Arduino With PHP
Controlling Arduino With PHP
Thomas Weinert
 

La actualidad más candente (20)

Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
dotCloud and go
dotCloud and godotCloud and go
dotCloud and go
 
Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
 
Controlling Arduino With PHP
Controlling Arduino With PHPControlling Arduino With PHP
Controlling Arduino With PHP
 
ZeroMQ Is The Answer
ZeroMQ Is The AnswerZeroMQ Is The Answer
ZeroMQ Is The Answer
 
Redis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your applicationRedis & ZeroMQ: How to scale your application
Redis & ZeroMQ: How to scale your application
 
JavaScript Promise
JavaScript PromiseJavaScript Promise
JavaScript Promise
 
Perl Web Client
Perl Web ClientPerl Web Client
Perl Web Client
 
Nubilus Perl
Nubilus PerlNubilus Perl
Nubilus Perl
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
PyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for TornadoPyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for Tornado
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS
 
ZeroMQ Is The Answer: DPC 11 Version
ZeroMQ Is The Answer: DPC 11 VersionZeroMQ Is The Answer: DPC 11 Version
ZeroMQ Is The Answer: DPC 11 Version
 
Bootstrapping multidc observability stack
Bootstrapping multidc observability stackBootstrapping multidc observability stack
Bootstrapping multidc observability stack
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous php
 

Similar a Any event intro

20 modules i haven't yet talked about
20 modules i haven't yet talked about20 modules i haven't yet talked about
20 modules i haven't yet talked about
Tatsuhiko Miyagawa
 
AnyMQ, Hippie, and the real-time web
AnyMQ, Hippie, and the real-time webAnyMQ, Hippie, and the real-time web
AnyMQ, Hippie, and the real-time web
clkao
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
優しいWAFの作り方
優しいWAFの作り方優しいWAFの作り方
優しいWAFの作り方
techmemo
 
Twib in Yokoahma.pm 2010/3/5
Twib in Yokoahma.pm 2010/3/5Twib in Yokoahma.pm 2010/3/5
Twib in Yokoahma.pm 2010/3/5
Yusuke Wada
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
Michael Peacock
 
Introduction to CloudForecast / YAPC::Asia 2010 Tokyo
Introduction to CloudForecast / YAPC::Asia 2010 TokyoIntroduction to CloudForecast / YAPC::Asia 2010 Tokyo
Introduction to CloudForecast / YAPC::Asia 2010 Tokyo
Masahiro Nagano
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Masahiro Nagano
 

Similar a Any event intro (20)

(DEV305) Building Apps with the AWS SDK for PHP | AWS re:Invent 2014
(DEV305) Building Apps with the AWS SDK for PHP | AWS re:Invent 2014(DEV305) Building Apps with the AWS SDK for PHP | AWS re:Invent 2014
(DEV305) Building Apps with the AWS SDK for PHP | AWS re:Invent 2014
 
20 modules i haven't yet talked about
20 modules i haven't yet talked about20 modules i haven't yet talked about
20 modules i haven't yet talked about
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
AnyMQ, Hippie, and the real-time web
AnyMQ, Hippie, and the real-time webAnyMQ, Hippie, and the real-time web
AnyMQ, Hippie, and the real-time web
 
Blog Hacks 2011
Blog Hacks 2011Blog Hacks 2011
Blog Hacks 2011
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!
 
Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers Cracow
 
Mojo as a_client
Mojo as a_clientMojo as a_client
Mojo as a_client
 
優しいWAFの作り方
優しいWAFの作り方優しいWAFの作り方
優しいWAFの作り方
 
Twib in Yokoahma.pm 2010/3/5
Twib in Yokoahma.pm 2010/3/5Twib in Yokoahma.pm 2010/3/5
Twib in Yokoahma.pm 2010/3/5
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
 
Reflex - How does it work?
Reflex - How does it work?Reflex - How does it work?
Reflex - How does it work?
 
Tatsumaki
TatsumakiTatsumaki
Tatsumaki
 
Introduction to CloudForecast / YAPC::Asia 2010 Tokyo
Introduction to CloudForecast / YAPC::Asia 2010 TokyoIntroduction to CloudForecast / YAPC::Asia 2010 Tokyo
Introduction to CloudForecast / YAPC::Asia 2010 Tokyo
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
 
10 tips for making Bash a sane programming language
10 tips for making Bash a sane programming language10 tips for making Bash a sane programming language
10 tips for making Bash a sane programming language
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Puppet @ Seat
Puppet @ SeatPuppet @ Seat
Puppet @ Seat
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

Any event intro

  • 1. AnyEvent Achilles Xu formalin14@gmail.com
  • 3. EV, libevent, POE, Glib, QT, Tk
  • 4. Hello World use AnyEvent; my $cv = AnyEvent->condvar; my $w = AnyEvent->timer( 'after' => 5, 'cb' => sub { print "hello worldn"; $cv->send; } ); $cv->recv;
  • 5. watcher I/O timer signal child process idle condvar AnyEvent::Handle AnyEvent::DNS AnyEvent::Socket
  • 6. I/O Watcher use AnyEvent; $| = 1; print "enter your name> "; my $name; my $wait_for_input = AnyEvent->io ( fh => *STDIN, # which file handle to check poll => "r", # which event to wait for ("r"ead data) cb => sub { # what callback to execute $name = <STDIN>; # read it } ); # do something else here
  • 7. Timer Watcher my $once_per_second = AnyEvent->timer ( after => 0, # first invoke ASAP interval => 1, # then invoke every second cb => sub { # the callback to invoke print "hin"; }, );
  • 9. Watcher use AnyEvent; sub aaa { my $w = AnyEvent->Timer( after => 3, interval => 5, cb => sub { print "hellon"; } ); } my $cv = AnyEvent->condvar; aaa(); $cv->recv; # won't print hello every 5 seconds.
  • 10. Watcher use AnyEvent; my $w; # Watcher sub aaa { $w = AnyEvent->Timer( after => 3, interval => 5, cb => sub { print "hellon"; } ); } my $cv = AnyEvent->condvar; aaa(); $cv->recv; # will print hello every 5 seconds.
  • 11. Watcher use AnyEvent; sub aaa { # watcher my $w; $w = AnyEvent->Timer( after => 3, interval => 5, cb => sub { print "hellon"; $w; } ); } my $cv = AnyEvent->condvar; aaa(); $cv->recv; # will print hello every 5 seconds.
  • 12. Watcher use AnyEvent; sub aaa { my $w; $w = AnyEvent->timer( after => 5, cb => sub { print "hellon"; undef $w; }); } aaa(); AnyEvent->condvar()->recv();
  • 13. CondVar main loop POE::Kernal->run(); $thread->join(); “This module is an AnyEvent user, you need to make sure that you use and run a supported event loop.”
  • 14. CondVar use AnyEvent; my $w = AnyEvent->timer( after => 0, interval => 5, cb => sub { print "hellon"; } ); my $cv = AnyEvent->condvar; $cv->recv; # just like while (1) {...}
  • 15. CondVar use AnyEvent; use AnyEvent::HTTP; # ... my @cvs; for (1 .. 5) { my $cv = AnyEvent->condvar; # like thread id push @cvs, $cv; http_get("http://some_url", sub { $cv->send; # like return in thread func }); } $_->recv for @cvs; # like $_->join for @threads; # ...
  • 16. closure PP Par::Packer perl -T
  • 17. use AnyEvent; my $x = "Tom"; AnyEvent->timer(afer => 5, cb => sub { print "hello $x"; }
  • 18. use AnyEvent; use AnyEvent::Handle; my $cv = AnyEvent->condvar; my $hdl; $hdl = new AnyEvent::Handle fh => *STDIN, on_error => sub { my ($hdl, $fatal, $msg) = @_; warn "got error $msgn"; $hdl->destroy; $cv->send; }; # send some request line $hdl->push_write ("getinfo015012"); # read the response line $hdl->push_read (line => sub { my ($hdl, $line) = @_; warn "got line <$line>n"; $cv->send; }); $cv->recv;
  • 19. use AnyEvent; use AnyEvent::HTTP; my $cv = AnyEvent->condvar; http_get("http://www.sina.com.cn", # watcher sub { my ($data, $headers) = @_; print $headers->{Status}, "n"; print $data, "n"; $cv->send; }); $cv->recv;
  • 20. use AnyEvent; # not AE # file handle or descriptor readable my $w = AE::io $fh, 0, sub { ... }; # one-shot or repeating timers my $w = AE::timer $seconds, 0, sub { ... }; # once my $w = AE::timer $seconds, $interval, sub { ... }; # repeated print AE::now; # prints current event loop time print AE::time; # think Time::HiRes::time or simply CORE::time. my $cv = AE::cv;
  • 21.
  • 22. http_get_retry("http://www.sina.com.cn", max_retries => 3, sub { my ($data, $headers) = @_; if (defined $data) { print "load ok"; } else { print "try 3 times failed"; } });
  • 23. http_get_file("http://aaa.com/somefile.tar.gz", "/data/files/somefile.tar.gz", max_concurrent => 20, sub { my ($data, $headers) = @_; if (defined $data) { print "download ok"; } else { print "some error happens: " . $headers->{Status}; } });
  • 24. http_get( $url, sub { ... }); DNS Resolving TCP Connecting Sending Request Reading Response
  • 25. Bugs socket accept push_read rtimeout EV PurePerl
  • 26. Bug's Solution timer *AE::now = sub { return AE::time; } *AE::now = *AE::time doesn't work