简体   繁体   English

asyncio,任务在哪里执行?

[英]asyncio, where Tasks are executed?

I'm new to asyncio.我是 asyncio 的新手。 Reading asyncio documentation , I don't understand where Tasks are run.阅读asyncio 文档,我不明白任务在哪里运行。

import asyncio

async def query_api(url):
    #http://a.b.c takes 3 seconds
    #http://x.y.z takes 5 seconds

async def main():
    task1 = asyncio.create_task(query_api('http://a.b.c'))
    task2 = asyncio.create_task(query_api('http://x.y.z'))
    
    await task1
    await task2
    print ('Tasks Done')

asyncio.run(main())

This doc says asyncio has an event loop running in a main thread. 这个文档说 asyncio 有一个在主线程中运行的事件循环。

  • Do task1 and task2 run in the main thread? task1task2在主线程中运行吗? If so, they must not run in parallel because CPU can only do one thing at a time?如果是这样,它们一定不能并行运行,因为 CPU 一次只能做一件事吗?
  • Tasks Done appears after 8 seconds or sooner? 8 秒后或更早出现Tasks Done

AsyncIO is a framework to run concurrent tasks. AsyncIO 是一个运行concurrent任务的框架。 Please note that Concurrency does not mean parallelism here.请注意,这里的并发并不意味着并行。

  • Do task1 and task2 run in the main thread? task1 和 task2 在主线程中运行吗? If so, they must not run in parallel because CPU can only do one thing at a time?如果是这样,它们一定不能并行运行,因为 CPU 一次只能做一件事吗?

Yes.是的。 They run in the same thread (by default) and it means that the they use the same CPU.它们运行在同一个线程中(默认情况下),这意味着它们使用相同的 CPU。 But the trick is that we do not need to hold on to the CPU while we are doing network I/O.但诀窍是我们在进行网络 I/O 时不需要占用 CPU。

Task2 can start using the CPU when Task1 is waiting on network to respond.当任务 1 在网络上等待响应时,任务 2 可以开始使用 CPU。

  • Tasks Done appears after 8 seconds or sooner? 8 秒后或更早出现任务完成?

The tasks should finish before 8 seconds任务应该在 8 秒之前完成

There are ways to use multi-threading or multi-processing using asyncIO if you require your tasks to be run outside your main thread.如果您需要在主线程之外运行任务,则可以通过 asyncIO 使用多线程或多处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM