SlideShare une entreprise Scribd logo
1  sur  35
Télécharger pour lire hors ligne
PSS Guest Lecture


Asynchronous IO 
  Programming

         th
       20  April 2006

  by Henrik Thostrup Jensen   1
Outline
    Asynchronous IO
●

        What, why, when
    –
        What about threads
    –
    Programming Asynchronously
●

        Berkeley sockets, select, poll
    –
        epoll, KQueue
    –
        Posix AIO, libevent, Twisted
    –




                                         2
What is Asynchronous IO
    Also called event­driven or non­blocking
●


    Performing IO without blocking
●

        Changing blocking operations to be non­blocking
    –
        Requires program reorganization
    –
             The brain must follow
         ●


    The program must never block
●

        Instead ask what can be done without blocking
    –




                                                          3
Why Asynchronous IO
    Concurrency is really difficult
●

        Coordinating threads and locks is non­trivial
    –
        Very non­trivial
    –
        Don't make things hard
    –
    Threads and locks are not free
●

        They take up resources and require kernel switches
    –
    Often true concurrency is not needed
●


    Asynchronous programs are race free
●

        By definition
    –


                                                             4
Drawbacks
    The program must not block
●

        Only a problem when learning
    –
        And with crappy APIs
    –
    Removes “normal” program flow
●

        Due to mixing of IO channels
    –
        Requires state machinery or continuations
    –
    Hard to use multiple CPU cores
●

        But doable
    –




                                                    5
Program Structure
    One process must handle several sockets
●

        State is not shared between connections
    –
        Often solved using state machines
    –
        Makes program flow more restricted
    –
    Debugging is different – but not harder
●

        Threads and locks are darn hard to debug
    –




                                                   6
Avoiding Asynchronous IO
    Not suitable for everything
●


    When true concurrency is needed
●

        Very seldom
    –
        Utilizing several CPUs with shared data
    –
    Or when badly suited
●

        Long running computations
    –
             Can be split, but bad abstraction
         ●




                                                  7
Are Threads Evil
    No ­ just misunderstood
●

        Used when inappropriate
    –
    Coordination is the problem
●

        Often goes wrong
    –
    Not free
●

        Spawning a thread for each incoming connection
    –
        500 incoming connections per second => problem
    –
        Thread pools used for compensating
    –




                                                         8
Setting Things Straight
    Async. IO and threads can do the same
●

        Probably includes performance
    –
    It's about having the best abstraction
●

        Or: Making things easy
    –
        Concurrency is not known to simplify things
    –




                                                      9
Async. Programming
    First introduced with Berkeley sockets
●


    Then came select, later poll
●


    Recent trends
●

        epoll, KQueue, Posix AIO, Twisted
    –




                                             10
Berkeley Sockets

    int s = socket(family, type, protocol);
    fcntl(s, F_SETFL, O_NONBLOCK);
    // bind+listen or connect (also async.)
    void *buffer = malloc(1024);
    retval = read(s, buffer, 1024);
    if (retval == -EAGAIN) {
       // Reschedule command
    }

    Unsuitable for many sockets
●

         Many kernel switches
     –
         The try/except paradigm is ill suited for IO
     –


                                                        11
Select

    int select(int n, fd_set *readfds, fd_set *writefds,
               fd_set *exceptfds, struct timeval *timeout);




    Monitors three sets of file descriptors for changes
●

         Tell which actions can be done without blocking
     –
    pselect() variant to avoid signal race
●


    Has a limit of of maximum file descriptors
●


    Availability: *nix, BSD, Windows
●

         Reasonably portable
     –

                                                              12
Poll

    int poll(struct pollfd *ufds, unsigned int nfds, int timeout);
    struct pollfd {
            int fd;           /* file descriptor */
            short events;     /* requested events */
            short revents;    /* returned events */
    };


    Basically a select() with a different API
●


    No limit on file descriptors
●


    Availability: *nix, BSD
●




                                                             13
State vs. Stateless
    select() and poll() is stateless
●

        This forces them to be O(n) operations
    –
             The kernel must scan all file descriptors
         ●


        This tend to suck for large number of file descriptors
    –
    Having state means more code in the kernel
●

        Continuously monitor a set of file descriptions
    –
        Makes an O(n) operation to O(1)
    –




                                                             14
Epoll 1/2

int epfd = epoll_create(EPOLL_QUEUE_LEN);
int client_sock = socket();
static struct epoll_event ev;
ev.events = EPOLLIN | EPOLLOUT | EPOLLERR;
ev.data.fd = client_sock;
int res = epoll_ctl(epfd, EPOLL_CTL_ADD, client_sock, &ev);
// Main loop
struct epoll_event *events;
while (1) {
    int nfds = epoll_wait(epfd, events, MAX_EVENTS, TIMEOUT);
    for(int i = 0; i < nfds; i++) {
        int fd = events[i].data.fd;
        handle_io_on_socket(fd);
    }
}
                                                          15
Epoll 2/2
    Has state in the kernel
●

        File descriptors must be added and removed
    –
        Slight more complex API
    –
    Outperforms select and poll
●

        When the number of open files is high
    –
    Availability: Linux only (introduced in 2.5)
●




                                                     16
KQueue
    We've had enough APIs for now
●


    Works much like epoll
●


    Also does disk IO, signals, file/process events
●


    Arguably best interface
●


    Availability: BSD
●




                                                      17
libevent
    Event based library
●

        Portable (Linux, BSD, Solaris, Windows)
    –
        Slightly better abstraction
    –
    Can use select, poll, epoll, KQueue, /dev/poll
●

        Possible to change between them
    –
    Can also be used for benchmarking :­)
●




                                                     18
libevent benchmark 1/2




                         19
libevent benchmark 2/2




                         20
Asynchronous Disk IO
    What about disk IO
●

        Often blocks so little time that it can be ignored
    –
        But sometimes it cannot
    –
    Databases are the prime target
●


    Sockets has been asynchronous for many years
●

        With disk IO limping behind
    –
    Posix AIO to the rescue
●




                                                             21
Posix AIO
    Relatively new standard
●

         Introduced in Linux in 2005
     –
              Was in several vendor trees before that
          ●


         Often emulated in libc using threads
     –
    Also does vector operations
●


    API Sample:
●

    int aio_read(struct aiocb *aiocbp);
    int aio_suspend(const struct aiocb* const iocbs[],
                    int niocb, const struct timespec *timeout);




                                                             22
Twisted
    An event­driven framework
●


    Lives at: www.twistedmatrix.com
●


    Started as game network library
●


    Rather large
●

        Around 200K lines of Python
    –
        Basic support for 30+ protocols
    –
    Has web, mail, ssh clients and servers
●


    Also has its own database API
●


    And security infrastructure (pluggable)
●



                                              23
Twisted vs. the world
    Probably most advanced framework in its class
●


    Only real competitor is ACE 
●

        Twisted borrows a lot of inspiration from here
    –
        ACE is also historically important
    –
    Some claim that java.nio and C# Async are also 
●


    asynchronous frameworks




                                                         24
Twisted Architecture
    Tries hard to keep things orthogonal
●


    Reactor–Transport–Factory–Protocol­Application
●

        As opposed to mingled together libraries
    –
    Makes changes very easy (once mastered)
●

        Often is about combining things the right way
    –
        Also means more boilerplate code
    –




                                                        25
Twisted Echo Server
    from twisted.internet import reactor, protocol

    class Echo(protocol.Protocol):
        def dataReceived(self, data):
            self.transport.write(data)

    factory = protocol.ServerFactory()
    factory.protocol = Echo
    reactor.listenTCP(8000, factory)
    reactor.run()

    Lots of magic behind the curtain
●

         Protocols, Factories and the Reactor
     –


                                                     26
The Twisted Reactor
    The main loop of Twisted
●


    Don't call us, we'll call you (framework)
●

        You insert code into the reactor
    –
    Also does scheduling
●

        Future calls, looping calls
    –
    Interchangeable
●

        select, poll, WMFO, IOCP, CoreFoundation, KQueue
    –
        Integrates with GTK, Qt, wxWidgets
    –




                                                      27
Factories and Protocols
    Factories produces protocols
●

        On incoming connections
    –
    A protocol represents a connection
●

        Provides method such as dataReceived
    –
        Which are called from the reactor
    –
    The application is build on top of protocols
●

        May use several transports, factories, and protocols
    –




                                                               28
Twisted Deferreds
    The single most confusing aspect in Twisted
●

        Removes the concept of stack execution
    –
    Vital to understand as they are the program flow
●

        An alternative to state machines
    –
    Think of them as a one­shot continuation
●

        Or: An object representing what should happen
    –
        Or: A promise that data will be delivered
    –
        Or: A callback
    –




                                                        29
Deferred Example
    Fetching a web page:
●


    def gotPage(page):
        print quot;I got the page:quot;, page

    deferred = twisted.web.getPage(quot;http://www.cs.aau.dk/quot;)
    deferred.addCallback(gotPage)
    return deferred

    The getPage function takes time to complete
●

         But blocking is prohibited
     –
    When the page is retrieve the deferred will fire
●

         And callbacks will be invoked
     –

                                                              30
Deferreds and Errors

    def gotPage(page):
        print quot;I got the page:quot;, page

    def getPage_errorback(error):
        print quot;Didn't get the page, me so sad - reason:quot;, error

    deferred = twisted.web.getPage(quot;http://www.cs.aau.dk/quot;)
    deferred.addCallback(gotPage)
    deferred.addErrback(getPage_errorback)

    Separates normal program flow from error 
●


    handling

                                                              31
Chaining Callbacks
    deferred = twisted.web.getPage(quot;http://www.cs.aau.dk/quot;)
    deferred.addCallback(gotPage)
    deferred.addCallback(changePage)
    deferred.addCallback(uploadPage)


    Often several sequential actions are needed
●


    The result from gotPage is provided as argument 
●


    to changePage
    The execution stack disappears
●

         Causes headaches during learning
     –
         Coroutines can make program more stack­like
     –

                                                              32
Deferreds and Coroutines
    @defer.deferredGenerator
    def myFunction(self):
        d = getPageStream(quot;http://www.cs.aau.dkquot;)
        yield d ; stream = d.getResult()
        while True:
            d = stream.read()
            yield d ; content = d.getResult()
            if content is None:
                break
            print content

    Notice: yield instead of return
●

         The function is reentrant
     –


                                                    33
Why Twisted
    Grasping the power of Twisted is difficult
●

        Also hard to explain
    –
    Makes cross protocol integration very easy
●


    Provides a lot of functionality and power
●

        But one needs to know how to use it
    –
    Drawbacks
●

        Steep learning curve
    –
        Portability: Applications cannot be ported to Twisted
    –




                                                           34
Summary
    Asynchronous IO
●

        An alternative to threads
    –
        Never block
    –
        Requires program reorganization
    –
    Asynchronous Programming
●

        Stateless: Berkeley sockets, select, poll
    –
        State: epoll, Kqueue
    –
        Disk: Posix AIO
    –
        libevent and Twisted
    –
    Exercises?
●


                                                    35

Contenu connexe

Tendances

HTTP/2, HTTP/3 and SSL/TLS State of the Art in Our Servers
HTTP/2, HTTP/3 and SSL/TLS State of the Art in Our ServersHTTP/2, HTTP/3 and SSL/TLS State of the Art in Our Servers
HTTP/2, HTTP/3 and SSL/TLS State of the Art in Our ServersJean-Frederic Clere
 
FreeBSD and Drivers
FreeBSD and DriversFreeBSD and Drivers
FreeBSD and DriversKernel TLV
 
SREConEurope15 - The evolution of the DHCP infrastructure at Facebook
SREConEurope15 - The evolution of the DHCP infrastructure at FacebookSREConEurope15 - The evolution of the DHCP infrastructure at Facebook
SREConEurope15 - The evolution of the DHCP infrastructure at FacebookAngelo Failla
 
Bypassing ASLR Exploiting CVE 2015-7545
Bypassing ASLR Exploiting CVE 2015-7545Bypassing ASLR Exploiting CVE 2015-7545
Bypassing ASLR Exploiting CVE 2015-7545Kernel TLV
 
Run Run Trema Test
Run Run Trema TestRun Run Trema Test
Run Run Trema TestHiroshi Ota
 
[2018.10.19] Andrew Kong - Tunnel without tunnel (Seminar at OpenStack Korea ...
[2018.10.19] Andrew Kong - Tunnel without tunnel (Seminar at OpenStack Korea ...[2018.10.19] Andrew Kong - Tunnel without tunnel (Seminar at OpenStack Korea ...
[2018.10.19] Andrew Kong - Tunnel without tunnel (Seminar at OpenStack Korea ...OpenStack Korea Community
 
5. hands on - building local development environment with Open Mano
5. hands on - building local development environment with Open Mano5. hands on - building local development environment with Open Mano
5. hands on - building local development environment with Open Manovideos
 
Troubleshooting common oslo.messaging and RabbitMQ issues
Troubleshooting common oslo.messaging and RabbitMQ issuesTroubleshooting common oslo.messaging and RabbitMQ issues
Troubleshooting common oslo.messaging and RabbitMQ issuesMichael Klishin
 
Improving the ZFS Userland-Kernel API with Channel Programs - BSDCAN 2017 - M...
Improving the ZFS Userland-Kernel API with Channel Programs - BSDCAN 2017 - M...Improving the ZFS Userland-Kernel API with Channel Programs - BSDCAN 2017 - M...
Improving the ZFS Userland-Kernel API with Channel Programs - BSDCAN 2017 - M...Matthew Ahrens
 
Pipework: Software-Defined Network for Containers and Docker
Pipework: Software-Defined Network for Containers and DockerPipework: Software-Defined Network for Containers and Docker
Pipework: Software-Defined Network for Containers and DockerJérôme Petazzoni
 
FBTFTP: an opensource framework to build dynamic tftp servers
FBTFTP: an opensource framework to build dynamic tftp serversFBTFTP: an opensource framework to build dynamic tftp servers
FBTFTP: an opensource framework to build dynamic tftp serversAngelo Failla
 
Open v switch20150410b
Open v switch20150410bOpen v switch20150410b
Open v switch20150410bRichard Kuo
 
Automated Deployment & Benchmarking with Chef, Cobbler and Rally for OpenStack
Automated Deployment & Benchmarking with Chef, Cobbler and Rally for OpenStackAutomated Deployment & Benchmarking with Chef, Cobbler and Rally for OpenStack
Automated Deployment & Benchmarking with Chef, Cobbler and Rally for OpenStackNTT Communications Technology Development
 
VLANs in the Linux Kernel
VLANs in the Linux KernelVLANs in the Linux Kernel
VLANs in the Linux KernelKernel TLV
 
Twisted Introduction
Twisted IntroductionTwisted Introduction
Twisted Introductioncyli
 
IPTABLES_linux_Firewall_Administration (1).pdf
IPTABLES_linux_Firewall_Administration (1).pdfIPTABLES_linux_Firewall_Administration (1).pdf
IPTABLES_linux_Firewall_Administration (1).pdfmpassword
 

Tendances (20)

HTTP/2, HTTP/3 and SSL/TLS State of the Art in Our Servers
HTTP/2, HTTP/3 and SSL/TLS State of the Art in Our ServersHTTP/2, HTTP/3 and SSL/TLS State of the Art in Our Servers
HTTP/2, HTTP/3 and SSL/TLS State of the Art in Our Servers
 
FreeBSD and Drivers
FreeBSD and DriversFreeBSD and Drivers
FreeBSD and Drivers
 
How we use Twisted in Launchpad
How we use Twisted in LaunchpadHow we use Twisted in Launchpad
How we use Twisted in Launchpad
 
SREConEurope15 - The evolution of the DHCP infrastructure at Facebook
SREConEurope15 - The evolution of the DHCP infrastructure at FacebookSREConEurope15 - The evolution of the DHCP infrastructure at Facebook
SREConEurope15 - The evolution of the DHCP infrastructure at Facebook
 
Bypassing ASLR Exploiting CVE 2015-7545
Bypassing ASLR Exploiting CVE 2015-7545Bypassing ASLR Exploiting CVE 2015-7545
Bypassing ASLR Exploiting CVE 2015-7545
 
Run Run Trema Test
Run Run Trema TestRun Run Trema Test
Run Run Trema Test
 
[2018.10.19] Andrew Kong - Tunnel without tunnel (Seminar at OpenStack Korea ...
[2018.10.19] Andrew Kong - Tunnel without tunnel (Seminar at OpenStack Korea ...[2018.10.19] Andrew Kong - Tunnel without tunnel (Seminar at OpenStack Korea ...
[2018.10.19] Andrew Kong - Tunnel without tunnel (Seminar at OpenStack Korea ...
 
From a cluster to the Cloud
From a cluster to the CloudFrom a cluster to the Cloud
From a cluster to the Cloud
 
5. hands on - building local development environment with Open Mano
5. hands on - building local development environment with Open Mano5. hands on - building local development environment with Open Mano
5. hands on - building local development environment with Open Mano
 
Troubleshooting common oslo.messaging and RabbitMQ issues
Troubleshooting common oslo.messaging and RabbitMQ issuesTroubleshooting common oslo.messaging and RabbitMQ issues
Troubleshooting common oslo.messaging and RabbitMQ issues
 
Improving the ZFS Userland-Kernel API with Channel Programs - BSDCAN 2017 - M...
Improving the ZFS Userland-Kernel API with Channel Programs - BSDCAN 2017 - M...Improving the ZFS Userland-Kernel API with Channel Programs - BSDCAN 2017 - M...
Improving the ZFS Userland-Kernel API with Channel Programs - BSDCAN 2017 - M...
 
Pipework: Software-Defined Network for Containers and Docker
Pipework: Software-Defined Network for Containers and DockerPipework: Software-Defined Network for Containers and Docker
Pipework: Software-Defined Network for Containers and Docker
 
FBTFTP: an opensource framework to build dynamic tftp servers
FBTFTP: an opensource framework to build dynamic tftp serversFBTFTP: an opensource framework to build dynamic tftp servers
FBTFTP: an opensource framework to build dynamic tftp servers
 
Open v switch20150410b
Open v switch20150410bOpen v switch20150410b
Open v switch20150410b
 
Automated Deployment & Benchmarking with Chef, Cobbler and Rally for OpenStack
Automated Deployment & Benchmarking with Chef, Cobbler and Rally for OpenStackAutomated Deployment & Benchmarking with Chef, Cobbler and Rally for OpenStack
Automated Deployment & Benchmarking with Chef, Cobbler and Rally for OpenStack
 
VLANs in the Linux Kernel
VLANs in the Linux KernelVLANs in the Linux Kernel
VLANs in the Linux Kernel
 
Twisted Introduction
Twisted IntroductionTwisted Introduction
Twisted Introduction
 
netty_qcon_v4
netty_qcon_v4netty_qcon_v4
netty_qcon_v4
 
OVS-NFV Tutorial
OVS-NFV TutorialOVS-NFV Tutorial
OVS-NFV Tutorial
 
IPTABLES_linux_Firewall_Administration (1).pdf
IPTABLES_linux_Firewall_Administration (1).pdfIPTABLES_linux_Firewall_Administration (1).pdf
IPTABLES_linux_Firewall_Administration (1).pdf
 

Similaire à Asynchronous Io Programming

Using the big guns: Advanced OS performance tools for troubleshooting databas...
Using the big guns: Advanced OS performance tools for troubleshooting databas...Using the big guns: Advanced OS performance tools for troubleshooting databas...
Using the big guns: Advanced OS performance tools for troubleshooting databas...Nikolay Savvinov
 
You're Off the Hook: Blinding Security Software
You're Off the Hook: Blinding Security SoftwareYou're Off the Hook: Blinding Security Software
You're Off the Hook: Blinding Security SoftwareCylance
 
OSDC 2017 | Open POWER for the data center by Werner Fischer
OSDC 2017 | Open POWER for the data center by Werner FischerOSDC 2017 | Open POWER for the data center by Werner Fischer
OSDC 2017 | Open POWER for the data center by Werner FischerNETWAYS
 
OSDC 2017 - Werner Fischer - Open power for the data center
OSDC 2017 - Werner Fischer - Open power for the data centerOSDC 2017 - Werner Fischer - Open power for the data center
OSDC 2017 - Werner Fischer - Open power for the data centerNETWAYS
 
OSDC 2017 | Linux Performance Profiling and Monitoring by Werner Fischer
OSDC 2017 | Linux Performance Profiling and Monitoring by Werner FischerOSDC 2017 | Linux Performance Profiling and Monitoring by Werner Fischer
OSDC 2017 | Linux Performance Profiling and Monitoring by Werner FischerNETWAYS
 
ParaForming - Patterns and Refactoring for Parallel Programming
ParaForming - Patterns and Refactoring for Parallel ProgrammingParaForming - Patterns and Refactoring for Parallel Programming
ParaForming - Patterns and Refactoring for Parallel Programmingkhstandrews
 
Embedded Linux Odp
Embedded Linux OdpEmbedded Linux Odp
Embedded Linux Odpghessler
 
Sanger OpenStack presentation March 2017
Sanger OpenStack presentation March 2017Sanger OpenStack presentation March 2017
Sanger OpenStack presentation March 2017Dave Holland
 
Brief Introduction to Parallella
Brief Introduction to ParallellaBrief Introduction to Parallella
Brief Introduction to ParallellaSomnath Mazumdar
 
Experiences building a distributed shared log on RADOS - Noah Watkins
Experiences building a distributed shared log on RADOS - Noah WatkinsExperiences building a distributed shared log on RADOS - Noah Watkins
Experiences building a distributed shared log on RADOS - Noah WatkinsCeph Community
 
Scylla Summit 2018: Make Scylla Fast Again! Find out how using Tools, Talent,...
Scylla Summit 2018: Make Scylla Fast Again! Find out how using Tools, Talent,...Scylla Summit 2018: Make Scylla Fast Again! Find out how using Tools, Talent,...
Scylla Summit 2018: Make Scylla Fast Again! Find out how using Tools, Talent,...ScyllaDB
 
Building SuperComputers @ Home
Building SuperComputers @ HomeBuilding SuperComputers @ Home
Building SuperComputers @ HomeAbhishek Parolkar
 
Scale11x lxc talk
Scale11x lxc talkScale11x lxc talk
Scale11x lxc talkdotCloud
 
Fault Tolerance in Spark: Lessons Learned from Production: Spark Summit East ...
Fault Tolerance in Spark: Lessons Learned from Production: Spark Summit East ...Fault Tolerance in Spark: Lessons Learned from Production: Spark Summit East ...
Fault Tolerance in Spark: Lessons Learned from Production: Spark Summit East ...Spark Summit
 
Intel Briefing Notes
Intel Briefing NotesIntel Briefing Notes
Intel Briefing NotesGraham Lee
 
Under The Hood Of A Shard-Per-Core Database Architecture
Under The Hood Of A Shard-Per-Core Database ArchitectureUnder The Hood Of A Shard-Per-Core Database Architecture
Under The Hood Of A Shard-Per-Core Database ArchitectureScyllaDB
 
Road to sbt 1.0 paved with server
Road to sbt 1.0   paved with serverRoad to sbt 1.0   paved with server
Road to sbt 1.0 paved with serverEugene Yokota
 
Sparkly Notebook: Interactive Analysis and Visualization with Spark
Sparkly Notebook: Interactive Analysis and Visualization with SparkSparkly Notebook: Interactive Analysis and Visualization with Spark
Sparkly Notebook: Interactive Analysis and Visualization with Sparkfelixcss
 

Similaire à Asynchronous Io Programming (20)

Using the big guns: Advanced OS performance tools for troubleshooting databas...
Using the big guns: Advanced OS performance tools for troubleshooting databas...Using the big guns: Advanced OS performance tools for troubleshooting databas...
Using the big guns: Advanced OS performance tools for troubleshooting databas...
 
You're Off the Hook: Blinding Security Software
You're Off the Hook: Blinding Security SoftwareYou're Off the Hook: Blinding Security Software
You're Off the Hook: Blinding Security Software
 
Os Wilhelm
Os WilhelmOs Wilhelm
Os Wilhelm
 
OSDC 2017 | Open POWER for the data center by Werner Fischer
OSDC 2017 | Open POWER for the data center by Werner FischerOSDC 2017 | Open POWER for the data center by Werner Fischer
OSDC 2017 | Open POWER for the data center by Werner Fischer
 
OSDC 2017 - Werner Fischer - Open power for the data center
OSDC 2017 - Werner Fischer - Open power for the data centerOSDC 2017 - Werner Fischer - Open power for the data center
OSDC 2017 - Werner Fischer - Open power for the data center
 
OSDC 2017 | Linux Performance Profiling and Monitoring by Werner Fischer
OSDC 2017 | Linux Performance Profiling and Monitoring by Werner FischerOSDC 2017 | Linux Performance Profiling and Monitoring by Werner Fischer
OSDC 2017 | Linux Performance Profiling and Monitoring by Werner Fischer
 
ParaForming - Patterns and Refactoring for Parallel Programming
ParaForming - Patterns and Refactoring for Parallel ProgrammingParaForming - Patterns and Refactoring for Parallel Programming
ParaForming - Patterns and Refactoring for Parallel Programming
 
Containers > VMs
Containers > VMsContainers > VMs
Containers > VMs
 
Embedded Linux Odp
Embedded Linux OdpEmbedded Linux Odp
Embedded Linux Odp
 
Sanger OpenStack presentation March 2017
Sanger OpenStack presentation March 2017Sanger OpenStack presentation March 2017
Sanger OpenStack presentation March 2017
 
Brief Introduction to Parallella
Brief Introduction to ParallellaBrief Introduction to Parallella
Brief Introduction to Parallella
 
Experiences building a distributed shared log on RADOS - Noah Watkins
Experiences building a distributed shared log on RADOS - Noah WatkinsExperiences building a distributed shared log on RADOS - Noah Watkins
Experiences building a distributed shared log on RADOS - Noah Watkins
 
Scylla Summit 2018: Make Scylla Fast Again! Find out how using Tools, Talent,...
Scylla Summit 2018: Make Scylla Fast Again! Find out how using Tools, Talent,...Scylla Summit 2018: Make Scylla Fast Again! Find out how using Tools, Talent,...
Scylla Summit 2018: Make Scylla Fast Again! Find out how using Tools, Talent,...
 
Building SuperComputers @ Home
Building SuperComputers @ HomeBuilding SuperComputers @ Home
Building SuperComputers @ Home
 
Scale11x lxc talk
Scale11x lxc talkScale11x lxc talk
Scale11x lxc talk
 
Fault Tolerance in Spark: Lessons Learned from Production: Spark Summit East ...
Fault Tolerance in Spark: Lessons Learned from Production: Spark Summit East ...Fault Tolerance in Spark: Lessons Learned from Production: Spark Summit East ...
Fault Tolerance in Spark: Lessons Learned from Production: Spark Summit East ...
 
Intel Briefing Notes
Intel Briefing NotesIntel Briefing Notes
Intel Briefing Notes
 
Under The Hood Of A Shard-Per-Core Database Architecture
Under The Hood Of A Shard-Per-Core Database ArchitectureUnder The Hood Of A Shard-Per-Core Database Architecture
Under The Hood Of A Shard-Per-Core Database Architecture
 
Road to sbt 1.0 paved with server
Road to sbt 1.0   paved with serverRoad to sbt 1.0   paved with server
Road to sbt 1.0 paved with server
 
Sparkly Notebook: Interactive Analysis and Visualization with Spark
Sparkly Notebook: Interactive Analysis and Visualization with SparkSparkly Notebook: Interactive Analysis and Visualization with Spark
Sparkly Notebook: Interactive Analysis and Visualization with Spark
 

Plus de l xf

The Proactor Pattern
The Proactor PatternThe Proactor Pattern
The Proactor Patternl xf
 
Erlang Message Passing Concurrency, For The Win
Erlang  Message  Passing  Concurrency,  For  The  WinErlang  Message  Passing  Concurrency,  For  The  Win
Erlang Message Passing Concurrency, For The Winl xf
 
Comparing Cpp And Erlang For Motorola Telecoms Software
Comparing Cpp And Erlang For Motorola Telecoms SoftwareComparing Cpp And Erlang For Motorola Telecoms Software
Comparing Cpp And Erlang For Motorola Telecoms Softwarel xf
 
The Migration From Erlang To Otp A Case Study Of A Heavy Duty Tcpip Clients...
The Migration From Erlang To Otp   A Case Study Of A Heavy Duty Tcpip Clients...The Migration From Erlang To Otp   A Case Study Of A Heavy Duty Tcpip Clients...
The Migration From Erlang To Otp A Case Study Of A Heavy Duty Tcpip Clients...l xf
 
Messaging With Erlang And Jabber
Messaging With  Erlang And  JabberMessaging With  Erlang And  Jabber
Messaging With Erlang And Jabberl xf
 
Improving Robustness In Distributed Systems
Improving Robustness In Distributed SystemsImproving Robustness In Distributed Systems
Improving Robustness In Distributed Systemsl xf
 
Concurrency And Erlang
Concurrency And ErlangConcurrency And Erlang
Concurrency And Erlangl xf
 
Learning Erlang And Developing A Sip Server Stack With 30k Potential Users
Learning Erlang And Developing A Sip Server Stack With 30k Potential UsersLearning Erlang And Developing A Sip Server Stack With 30k Potential Users
Learning Erlang And Developing A Sip Server Stack With 30k Potential Usersl xf
 
A Virtual World Distributed Server Developed In Erlang As A Tool For Analysin...
A Virtual World Distributed Server Developed In Erlang As A Tool For Analysin...A Virtual World Distributed Server Developed In Erlang As A Tool For Analysin...
A Virtual World Distributed Server Developed In Erlang As A Tool For Analysin...l xf
 

Plus de l xf (9)

The Proactor Pattern
The Proactor PatternThe Proactor Pattern
The Proactor Pattern
 
Erlang Message Passing Concurrency, For The Win
Erlang  Message  Passing  Concurrency,  For  The  WinErlang  Message  Passing  Concurrency,  For  The  Win
Erlang Message Passing Concurrency, For The Win
 
Comparing Cpp And Erlang For Motorola Telecoms Software
Comparing Cpp And Erlang For Motorola Telecoms SoftwareComparing Cpp And Erlang For Motorola Telecoms Software
Comparing Cpp And Erlang For Motorola Telecoms Software
 
The Migration From Erlang To Otp A Case Study Of A Heavy Duty Tcpip Clients...
The Migration From Erlang To Otp   A Case Study Of A Heavy Duty Tcpip Clients...The Migration From Erlang To Otp   A Case Study Of A Heavy Duty Tcpip Clients...
The Migration From Erlang To Otp A Case Study Of A Heavy Duty Tcpip Clients...
 
Messaging With Erlang And Jabber
Messaging With  Erlang And  JabberMessaging With  Erlang And  Jabber
Messaging With Erlang And Jabber
 
Improving Robustness In Distributed Systems
Improving Robustness In Distributed SystemsImproving Robustness In Distributed Systems
Improving Robustness In Distributed Systems
 
Concurrency And Erlang
Concurrency And ErlangConcurrency And Erlang
Concurrency And Erlang
 
Learning Erlang And Developing A Sip Server Stack With 30k Potential Users
Learning Erlang And Developing A Sip Server Stack With 30k Potential UsersLearning Erlang And Developing A Sip Server Stack With 30k Potential Users
Learning Erlang And Developing A Sip Server Stack With 30k Potential Users
 
A Virtual World Distributed Server Developed In Erlang As A Tool For Analysin...
A Virtual World Distributed Server Developed In Erlang As A Tool For Analysin...A Virtual World Distributed Server Developed In Erlang As A Tool For Analysin...
A Virtual World Distributed Server Developed In Erlang As A Tool For Analysin...
 

Dernier

What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Dernier (20)

What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

Asynchronous Io Programming

  • 1. PSS Guest Lecture Asynchronous IO  Programming th 20  April 2006 by Henrik Thostrup Jensen 1
  • 2. Outline Asynchronous IO ● What, why, when – What about threads – Programming Asynchronously ● Berkeley sockets, select, poll – epoll, KQueue – Posix AIO, libevent, Twisted – 2
  • 3. What is Asynchronous IO Also called event­driven or non­blocking ● Performing IO without blocking ● Changing blocking operations to be non­blocking – Requires program reorganization – The brain must follow ● The program must never block ● Instead ask what can be done without blocking – 3
  • 4. Why Asynchronous IO Concurrency is really difficult ● Coordinating threads and locks is non­trivial – Very non­trivial – Don't make things hard – Threads and locks are not free ● They take up resources and require kernel switches – Often true concurrency is not needed ● Asynchronous programs are race free ● By definition – 4
  • 5. Drawbacks The program must not block ● Only a problem when learning – And with crappy APIs – Removes “normal” program flow ● Due to mixing of IO channels – Requires state machinery or continuations – Hard to use multiple CPU cores ● But doable – 5
  • 6. Program Structure One process must handle several sockets ● State is not shared between connections – Often solved using state machines – Makes program flow more restricted – Debugging is different – but not harder ● Threads and locks are darn hard to debug – 6
  • 7. Avoiding Asynchronous IO Not suitable for everything ● When true concurrency is needed ● Very seldom – Utilizing several CPUs with shared data – Or when badly suited ● Long running computations – Can be split, but bad abstraction ● 7
  • 8. Are Threads Evil No ­ just misunderstood ● Used when inappropriate – Coordination is the problem ● Often goes wrong – Not free ● Spawning a thread for each incoming connection – 500 incoming connections per second => problem – Thread pools used for compensating – 8
  • 9. Setting Things Straight Async. IO and threads can do the same ● Probably includes performance – It's about having the best abstraction ● Or: Making things easy – Concurrency is not known to simplify things – 9
  • 10. Async. Programming First introduced with Berkeley sockets ● Then came select, later poll ● Recent trends ● epoll, KQueue, Posix AIO, Twisted – 10
  • 11. Berkeley Sockets int s = socket(family, type, protocol); fcntl(s, F_SETFL, O_NONBLOCK); // bind+listen or connect (also async.) void *buffer = malloc(1024); retval = read(s, buffer, 1024); if (retval == -EAGAIN) { // Reschedule command } Unsuitable for many sockets ● Many kernel switches – The try/except paradigm is ill suited for IO – 11
  • 12. Select int select(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); Monitors three sets of file descriptors for changes ● Tell which actions can be done without blocking – pselect() variant to avoid signal race ● Has a limit of of maximum file descriptors ● Availability: *nix, BSD, Windows ● Reasonably portable – 12
  • 13. Poll int poll(struct pollfd *ufds, unsigned int nfds, int timeout); struct pollfd { int fd; /* file descriptor */ short events; /* requested events */ short revents; /* returned events */ }; Basically a select() with a different API ● No limit on file descriptors ● Availability: *nix, BSD ● 13
  • 14. State vs. Stateless select() and poll() is stateless ● This forces them to be O(n) operations – The kernel must scan all file descriptors ● This tend to suck for large number of file descriptors – Having state means more code in the kernel ● Continuously monitor a set of file descriptions – Makes an O(n) operation to O(1) – 14
  • 15. Epoll 1/2 int epfd = epoll_create(EPOLL_QUEUE_LEN); int client_sock = socket(); static struct epoll_event ev; ev.events = EPOLLIN | EPOLLOUT | EPOLLERR; ev.data.fd = client_sock; int res = epoll_ctl(epfd, EPOLL_CTL_ADD, client_sock, &ev); // Main loop struct epoll_event *events; while (1) { int nfds = epoll_wait(epfd, events, MAX_EVENTS, TIMEOUT); for(int i = 0; i < nfds; i++) { int fd = events[i].data.fd; handle_io_on_socket(fd); } } 15
  • 16. Epoll 2/2 Has state in the kernel ● File descriptors must be added and removed – Slight more complex API – Outperforms select and poll ● When the number of open files is high – Availability: Linux only (introduced in 2.5) ● 16
  • 17. KQueue We've had enough APIs for now ● Works much like epoll ● Also does disk IO, signals, file/process events ● Arguably best interface ● Availability: BSD ● 17
  • 18. libevent Event based library ● Portable (Linux, BSD, Solaris, Windows) – Slightly better abstraction – Can use select, poll, epoll, KQueue, /dev/poll ● Possible to change between them – Can also be used for benchmarking :­) ● 18
  • 21. Asynchronous Disk IO What about disk IO ● Often blocks so little time that it can be ignored – But sometimes it cannot – Databases are the prime target ● Sockets has been asynchronous for many years ● With disk IO limping behind – Posix AIO to the rescue ● 21
  • 22. Posix AIO Relatively new standard ● Introduced in Linux in 2005 – Was in several vendor trees before that ● Often emulated in libc using threads – Also does vector operations ● API Sample: ● int aio_read(struct aiocb *aiocbp); int aio_suspend(const struct aiocb* const iocbs[], int niocb, const struct timespec *timeout); 22
  • 23. Twisted An event­driven framework ● Lives at: www.twistedmatrix.com ● Started as game network library ● Rather large ● Around 200K lines of Python – Basic support for 30+ protocols – Has web, mail, ssh clients and servers ● Also has its own database API ● And security infrastructure (pluggable) ● 23
  • 24. Twisted vs. the world Probably most advanced framework in its class ● Only real competitor is ACE  ● Twisted borrows a lot of inspiration from here – ACE is also historically important – Some claim that java.nio and C# Async are also  ● asynchronous frameworks 24
  • 25. Twisted Architecture Tries hard to keep things orthogonal ● Reactor–Transport–Factory–Protocol­Application ● As opposed to mingled together libraries – Makes changes very easy (once mastered) ● Often is about combining things the right way – Also means more boilerplate code – 25
  • 26. Twisted Echo Server from twisted.internet import reactor, protocol class Echo(protocol.Protocol): def dataReceived(self, data): self.transport.write(data) factory = protocol.ServerFactory() factory.protocol = Echo reactor.listenTCP(8000, factory) reactor.run() Lots of magic behind the curtain ● Protocols, Factories and the Reactor – 26
  • 27. The Twisted Reactor The main loop of Twisted ● Don't call us, we'll call you (framework) ● You insert code into the reactor – Also does scheduling ● Future calls, looping calls – Interchangeable ● select, poll, WMFO, IOCP, CoreFoundation, KQueue – Integrates with GTK, Qt, wxWidgets – 27
  • 28. Factories and Protocols Factories produces protocols ● On incoming connections – A protocol represents a connection ● Provides method such as dataReceived – Which are called from the reactor – The application is build on top of protocols ● May use several transports, factories, and protocols – 28
  • 29. Twisted Deferreds The single most confusing aspect in Twisted ● Removes the concept of stack execution – Vital to understand as they are the program flow ● An alternative to state machines – Think of them as a one­shot continuation ● Or: An object representing what should happen – Or: A promise that data will be delivered – Or: A callback – 29
  • 30. Deferred Example Fetching a web page: ● def gotPage(page): print quot;I got the page:quot;, page deferred = twisted.web.getPage(quot;http://www.cs.aau.dk/quot;) deferred.addCallback(gotPage) return deferred The getPage function takes time to complete ● But blocking is prohibited – When the page is retrieve the deferred will fire ● And callbacks will be invoked – 30
  • 31. Deferreds and Errors def gotPage(page): print quot;I got the page:quot;, page def getPage_errorback(error): print quot;Didn't get the page, me so sad - reason:quot;, error deferred = twisted.web.getPage(quot;http://www.cs.aau.dk/quot;) deferred.addCallback(gotPage) deferred.addErrback(getPage_errorback) Separates normal program flow from error  ● handling 31
  • 32. Chaining Callbacks deferred = twisted.web.getPage(quot;http://www.cs.aau.dk/quot;) deferred.addCallback(gotPage) deferred.addCallback(changePage) deferred.addCallback(uploadPage) Often several sequential actions are needed ● The result from gotPage is provided as argument  ● to changePage The execution stack disappears ● Causes headaches during learning – Coroutines can make program more stack­like – 32
  • 33. Deferreds and Coroutines @defer.deferredGenerator def myFunction(self): d = getPageStream(quot;http://www.cs.aau.dkquot;) yield d ; stream = d.getResult() while True: d = stream.read() yield d ; content = d.getResult() if content is None: break print content Notice: yield instead of return ● The function is reentrant – 33
  • 34. Why Twisted Grasping the power of Twisted is difficult ● Also hard to explain – Makes cross protocol integration very easy ● Provides a lot of functionality and power ● But one needs to know how to use it – Drawbacks ● Steep learning curve – Portability: Applications cannot be ported to Twisted – 34
  • 35. Summary Asynchronous IO ● An alternative to threads – Never block – Requires program reorganization – Asynchronous Programming ● Stateless: Berkeley sockets, select, poll – State: epoll, Kqueue – Disk: Posix AIO – libevent and Twisted – Exercises? ● 35