async, await

Download Async, await

Post on 13-Apr-2017

249 views

Category:

Technology

0 download

Embed Size (px)

TRANSCRIPT

  • ASYNC, AWAITasynchronous |eskrns| (adj.)

    Adrian Liaw

  • Adrian Liawadrianliaw / adrianliaw2000http://github.com/adrianliaw

    http://github.com/adrianliaw

  • AGENDAWhat is asyncTraditional approachasyncio

  • PSEUDOCODEwhile not everyone is done:

    person = select 1st person in the queue

    if not check_homework(person):

    person.fill_blanks(do go_to_queue() when done)

  • WHAT IS ASYNCAsynchronous I/O or non-blocking I/OSingle-threaded

    Non-blocking sockets

    select, epoll, kqueue

    event loop"Tell me when you're done"

  • TRADITIONAL APPROACH

  • CALLBACKSfs.readFile("foo", "utf8", function (error, result) { if (!error) console.log(error); else console.log(result)});

  • CONS OF CALLBACKMessyHard to save stateHard to organiseBad for Python

  • GENERATOR

  • >>> def foo():... yield "foo"... yield "bar"

    >>> gen = foo()

    >>> gen

    >>> next(gen)"foo">>> next(gen)"bar"

    >>> next(gen)StopIteration:

  • >>> def foo():... bar = yield "foo"... baz = yield bar * 10

    >>> gen = foo()>>> next(gen)'foo'>>> gen.send(20)200>>> gen.throw(ValueError)ValueError:

  • >>> def foo():... baz = yield from bar()... print(baz)

    >>> def bar():... yield 1... yield 2... return "fooooo"

  • PEP 3156asyncio

  • @asyncio.coroutinedef coro_func(): print("Sleeping...") yield from asyncio.sleep(3) print("Done")

    loop = asyncio.get_event_loop()loop.run_until_complete(coro_func())

  • async def coro_func(): print("Sleeping...") await asyncio.sleep(3) print("Done")

    loop = asyncio.get_event_loop()loop.run_until_complete(coro_func())

  • asyncio + aiohttp =
  • REFERENCESPEP 3156bit.ly/coroutinesDavid Beazley - Python Concurrency From the Ground Up

    http://bit.ly/coroutineshttps://youtu.be/MCs5OvhV9S4

  • Q&A

Recommended

View more >