Achilles Xu
formalin14@gmail.com
Contents
•
•
•
•
•
•
•
•       I/O         CPU
    /         CPU


•                    I/O
        CPU
•
        /
•
•
    •
    •
• linux   win


•
•               top
    cpu
my @urllist = read_list();
my @pids;
for my $url (@urllist) {
   my $pid = fork();
   if ($pid == 0) {
       print get($url);
       exit;
   } elsif ($pid > 0) {
       push @pids, $pid; #        ID
  }
}
waitpid($_, ...) for @pids;   #
# do other nonconcurrent jobs
my @pids;
for ( 1 .. 20) {
   my $pid = fork;
   if ($pid == 0) {
       while (1) {
           my $task = lock_and_get_task();
           do_task($task);
           sleep 1;
       }
       exit;
   } elsif ($pid > 0) {
       push @pids, $pid;
   }
}
waitpid($_, ...) for @pids;
•
•   top       cpu


•     perl 5.8.5   perl 5.8.8
        LWP
use threads;
sub load_url {
    print get($_[0]);
}
my @urllist = read_url_list();
my @tids;
for my $url (@urllist) {
    my $tid = threads->create(&load_url, $url);
    push @tids, $tid;   #           ID
}
$_->join for @tids;         #              waitpid
# do other things
use threads;
use threads::shared;
my @queue : shared;
for (1 .. 6) {
   threads->create( sub {
      while (1) {
          my $task;
          { lock @queue;
            $task = shift @queue;
           }
           do_task($task);
           threads::sleep(1);
        }
    }
}
while (1) { generate_task(@queue); threads::sleep(1); }
java.lang.Thread


•    linux   windows


•
• C Python   GIL

• Coro       Coroutines

•
Coro

•   I/O      CPU

•     cede     CPU

•   Perl6            async
Coro
use Coro;


async {
   # some asynchronous thread of execution
   print "2n";
   cede; # yield back to main
   print "4n";
};
print "1n";
cede; # yield to coro
print "3n";
cede; # and again
•   I/O

•
•
•
• select
• poll select
• epoll               I/O

•               I/O
    sendfile
• POE
• Twisted
• AnyEvent
• Java NIO
POE
•
•              yield
•   Session


• $heap
•
POE
  sub handler_increment {
    my ($kernel, $heap, $session) = @_
[KERNEL, HEAP, SESSION];
    print "Session ", $session->ID, "
counted to ", ++$heap->{count}, ".n";
    $kernel->yield('increment') if
$heap->{count} < 10;
  }
Twisted
•
•
•     POE             N


•
•                       dns connect send
    request got first byte....       hook
•
Twisted
d = conect_to_server()
d.addCallback(login_user)
d.addErrback(reconnect_to_server)


reactor.run()
AnyEvent

•                   libevent
    EV

•
•
•   Coro POE
Java NIO

•   linux   windows


•                     Channel
• Squid 2.x
• Apache
• Nginx
Squid 2.x
•
•        sendfile

•
• COSS
•
Apache

•
•
•       php
Nginx

•
• epoll   kqueue   sendfile writev

•
•
• Questions

并发模型介绍