简体   繁体   English

基本异步未执行第二个任务

[英]Basic asyncio not executing second task

In this minimal example, I expect the program to print foo and fuu as the tasks are scheduled.在这个最小的示例中,我希望程序在安排任务时打印foofuu

import asyncio


async def coroutine():
        
    while True:
        print("foo")

async def main():

    asyncio.create_task(coroutine())
    #asyncio.run_coroutine_threadsafe(coroutine(),asyncio.get_running_loop())
    
    while True:
        print("fuu")

asyncio.run(main())

The program will only write fuu .该程序只会写fuu
My aim is to simply have two tasks executing concurrently, but it seems like the created task is never scheduled.我的目标是简单地让两个任务同时执行,但似乎创建的任务从未被安排。

I also tried using run_coroutine_threadsafe with no success.我也尝试使用run_coroutine_threadsafe没有成功。

If I add await asyncio.sleep(1) to the main.如果我将await asyncio.sleep(1)添加到主目录。 The created task takes the execution and the program will only write foo .创建的任务会执行,程序只会写foo

What I am supposed to do to run two tasks simultaneously using asyncio?我应该怎么做才能使用 asyncio 同时运行两个任务?

I love this question and the explanation of this question tells how asyncio and python works.我喜欢这个问题,这个问题的解释告诉我们 asyncio 和 python 是如何工作的。

Spoilers - It works similar to Javascript single threaded runtime.剧透- 它的工作方式类似于 Javascript 单线程运行时。

So, let's look at your code.所以,让我们看看你的代码。 You only have one main thread running which would be continuously running since python scheduler don't have to switch between threads.由于 python 调度程序不必在线程之间切换,因此您只有一个正在运行的主线程。 Now, the thing is, your main thread that creates a task actually creates a coroutine(green threads, managed by python scheduler and not OS scheduler) which needs main thread to get executed.现在,问题是,您创建任务的主线程实际上创建了一个协程(绿色线程,由 python 调度程序而不是 OS 调度程序管理),它需要主线程来执行。

Now the main thread is never free, since you have put while True , it is never free to execute anything else and your task never gets executed because python scheduler never does the switching because it is busy executing while True code.现在主线程永远不会空闲,因为您放置了while True ,所以它永远不会自由执行任何其他操作,并且您的任务永远不会被执行,因为 python 调度程序永远不会进行切换,因为它在 True代码中忙于执行。

The moment you put sleep, it detects that the current task is sleeping and it does the context switching and your coroutine kicks in.当你进入睡眠状态时,它会检测到当前任务正在睡眠,它会进行上下文切换,你的协程就会启动。

My suggestion.我的建议。 if your tasks are I/O heavy, use tasks/coroutines and if they are CPU heavy which is in your case ( while True ), create either Python Threads or Processes and then the OS scheduler will take care of running your tasks, they will get CPU slice to run while True .如果您的任务 I/O 繁重,请使用任务/协程,如果它们是 CPU 繁重(在您的情况下是while True ),请创建 Python 线程或进程,然后操作系统调度程序将负责运行您的任务,它们将让 CPU 片while True时运行。

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

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