异步IO解释

时间:2018-03-15 16:43:28

标签: python multithreading async-await

我正在阅读Python docs并找到了这个例子:

import asyncio
import datetime

async def display_date(loop):
    end_time = loop.time() + 5.0
    while True:
        print(datetime.datetime.now())
        if (loop.time() + 1.0) >= end_time:
            break
        await asyncio.sleep(1)

loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()

注意:上述代码中的注释表明loop.run_until_complete(display_date(loop))是阻止通话。

this教科书和相应的website,我找到了这个例子:

# asyncio_executor_thread.py

import asyncio
import concurrent.futures
import logging
import sys
import time


def blocks(n):
    log = logging.getLogger('blocks({})'.format(n))
    log.info('running')
    time.sleep(0.1)
    log.info('done')
    return n ** 2

async def run_blocking_tasks(executor):
    log = logging.getLogger('run_blocking_tasks')
    log.info('starting')

    log.info('creating executor tasks')
    loop = asyncio.get_event_loop()
    blocking_tasks = [
        loop.run_in_executor(executor, blocks, i)
        for i in range(6)
    ]
    log.info('waiting for executor tasks')
    completed, pending = await asyncio.wait(blocking_tasks)
    results = [t.result() for t in completed]
    log.info('results: {!r}'.format(results))

    log.info('exiting')

if __name__ == '__main__':
    # Configure logging to show the name of the thread
    # where the log message originates.
    logging.basicConfig(
        level=logging.INFO,
        format='%(threadName)10s %(name)18s: %(message)s',
        stream=sys.stderr,
    )

    # Create a limited thread pool.
    executor = concurrent.futures.ThreadPoolExecutor(
        max_workers=3,
    )

    event_loop = asyncio.get_event_loop()
    try:
        event_loop.run_until_complete(run_blocking_tasks(executor))
    finally:
        event_loop.close()

正如python docs中的第一个例子中所述,loop.run_until_complete()阻塞,这意味着它之后的任何代码,所以如果我有一个for循环打印数字从1到10,那个for循环赢了& #39; t执行直到loop.run_until_complete(display_date(loop))完成。

第二个示例在threadpoolexecutor内运行一个函数,并再次使用阻止调用event_loop.run_until_complete(run_blocking_tasks(executor)

问题:

  1. 从第二个例子开始,假设我想计算n ** 2 而不阻止主线程,我会创建一个线程,传递函数和参数,并start()线程,而主线程正在做其他事情,对吗?
  2. asyncloop.run_until_complete()threadpoolexecutor一起使用时,您可以为其提供一个函数和参数来运行,等待它完成,正确?在调用loop.run_until_complete()时,有一个理解是你在等待循环完成(因此函数名称)?我不应该调用loop.run_until_complete(),期望其后的任何代码都会执行该循环正在运行?

0 个答案:

没有答案