对并行任务使用异步

2022-03-25 00:00:00 python python-3.x python-asyncio

问题描述

我想知道如何使用Asyncio来处理与NodeJS类似的任务。我想在不打开线程的情况下同时运行任务。 示例:

import asyncio

@asyncio.coroutine
def my_coroutine(task_name, seconds_to_sleep=3):
    print('{0} sleeping for: {1} seconds'.format(task_name, seconds_to_sleep))
    yield from asyncio.sleep(seconds_to_sleep)
    print('{0} is finished'.format(task_name))


loop = asyncio.get_event_loop()
tasks = [
    my_coroutine('task1', 4),
    my_coroutine('task2', 3),
    my_coroutine('task3', 2)]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

将输出:

task1 sleeping for: 4 seconds
task2 sleeping for: 3 seconds
task3 sleeping for: 2 seconds
task3 is finished
task2 is finished
task1 is finished

但是,当我尝试使用不同的任务时,它不会像那样工作。

import asyncio
import timeit

@asyncio.coroutine
def my_coroutine(task_name):
    print('order placed for ' + task_name)
    print(timeit.timeit('1 + 3 ', number=50000000))
    print(task_name + ' done')


loop = asyncio.get_event_loop()
tasks = [
    my_coroutine('task1'),
    my_coroutine('task2'),
    my_coroutine('task3')]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

输出

order placed for task2
0.6677237730912453
task2 done
order placed for task1
0.6627442526498016
task1 done
order placed for task3
0.665618849882418
task3 done

解决方案

异步不并行运行。它运行一个任务,直到它等待,然后转到下一个任务。第一个示例中的sleep是使任务相互控制的原因。您的第二个示例不会等待任何东西,因此每个任务都会一直运行到完成,然后事件循环才能将控制权交给另一个任务。

如果您在协程中添加了一些可等待的内容(例如,asyncio.sleep),则每个都将放弃控制,并给其他人一个运行的机会。

@asyncio.coroutine
def my_coroutine(task_name):
    print('order placed for ' + task_name)
    yield from asyncio.sleep(0)  # Another coroutine will resume here.
    print(timeit.timeit('1 + 3 ', number=50000000))
    yield from asyncio.sleep(0)  # Another coroutine will resume here.
    print(task_name + ' done')

相关文章