Skip to content

asyncio #

Find similar titles

4회 업데이트 됨.

Edit
  • 최초 작성자
    Sardor
  • 최근 업데이트

Structured data

Category
Software

Overview #

asyncio is just Python library to write asynchronous programs. Asynchronous programs focus on handling concurrent operations as much as possible. To use asyncio it's required to have Python 3.5 or higher version.

Install #

asyncio is built-in library starting from Python 3.5, so there is no other ways to install it explicitly.

Getting started #

We should use Python 3.5 async and await keywords rather than @asyncio.coroutine and yield from.

Glossary #

coroutine #

A coroutine is a piece of code that can be paused and resumed. In contrast to threads which are preemptively multitasked by the operating system, coroutines multitask cooperatively. I.e. they choose when to pause (or to use terminology for coroutines before 3.4 - yield) execution. They can also execute other coroutines.

event loop #

The event loop is the central execution device to launch execution of coroutines and handle I/O (Network, sub-processes...)

future #

It’s like a mailbox where you can subscribe to receive a result when it will be done. More details in official documentation

task #

It represents the execution of a coroutine and take care the result in a future. More details in official documentation.

Example #

Simple coroutine #

import asyncio

async def say(what, when):
    await asyncio.sleep(when)
    print(what)

loop = asyncio.get_event_loop()
loop.run_until_complete(say('hello world', 1))
loop.close()

Creating tasks #

import asyncio

async def say(what, when):
    await asyncio.sleep(when)
    print(what)


loop = asyncio.get_event_loop()

loop.create_task(say('first hello', 2))
loop.create_task(say('second hello', 1))

loop.run_forever()
loop.close()

import asyncio

Stopping loop #

import asyncio

async def say(what, when):
    await asyncio.sleep(when)
    print(what)

async def stop_after(loop, when):
    await asyncio.sleep(when)
    loop.stop()


loop = asyncio.get_event_loop()

loop.create_task(say('first hello', 2))
loop.create_task(say('second hello', 1))
loop.create_task(say('third hello', 4))
loop.create_task(stop_after(loop, 3))

loop.run_forever()
loop.close()

Clock example #

async def print_every_second():
    "Print seconds"
    while True:
        for i in range(60):
            print(i, 's')
            await asyncio.sleep(1)


async def print_every_minute():
    for i in range(1, 10):
        await asyncio.sleep(60)
        print(i, 'minute')


loop = asyncio.get_event_loop()
loop.run_until_complete(
    asyncio.gather(print_every_second(),
                   print_every_minute())
)
loop.close()

References #

  1. https://docs.python.org/3/library/asyncio.html
  2. http://asyncio.readthedocs.io/en/latest/index.html
  3. http://soooprmx.com/wp/archives/6882
  4. https://www.pycon.kr/2014/program/4
  5. https://github.com/python/asyncio
0.0.1_20230725_7_v68