简体   繁体   English

uasyncio.create_task 不运行协程(micropython)

[英]uasyncio.create_task does not run coroutine (micropython)

Before I start an issue on github, just wanted to know, if I am doing smth wrong.在我开始关于 github 的问题之前,我只是想知道,如果我做错了。 This basic example should start a loop and after one calls the stop method it should stop.这个基本示例应该开始一个循环,并且在调用stop方法后它应该停止。 However, the print("while loop") gets not executed at all.但是,根本不执行print("while loop")

  • rp2040 Zero (Pico) rp2040 零(微微)
  • Thonny IDE刺客 IDE
import uasyncio
import utime

class Test:
    def __init__(self):
        pass
    
    def run_loop(self):
        self.should_run = 1
        uasyncio.create_task(self._while_loop())

    async def _while_loop(self):
        print("while loop") # <--------- gets never called!
        counter = 0
        while self.should_run == 1:
            counter += 1
            print(counter)
            await uasyncio.sleep_ms(100)
    
    def stop(self):
        self.should_run = 0
        print("should stop now")

test = Test()
test.run_loop()
print("looop started.. wait..")
utime.sleep(3)
print("...waited..")
test.stop()

In a python script all executions are sync by default.在 python脚本中,默认情况下所有执行都是同步的。 To provide async functionality one has to create an async context.要提供异步功能,必须创建一个异步上下文。 this is done via asyncio.run() // which will wait due to pythons nature till all inner async tasks are terminated.这是通过 asyncio.run() 完成的 // 由于 python 的性质,它将等待所有内部异步任务终止。

As the micropython-uasyncio docs says, a typical async application is wrapped into the async context (eg main function).正如micropython-uasyncio文档所说,一个典型的异步应用程序被包装到异步上下文中(例如main函数)。

This is how I solved the problem above:这就是我解决上述问题的方法:

import uasyncio as asyncio
import utime

class Test:
    run = 0
    def __init__(self):
        pass
    
    def run_loop(self):
        self.run = 1
        asyncio.create_task(self._while_loop())

    async def _while_loop(self):
        print("while loop, should_run:", self.run)
        counter = 0
        while self.run == 1:
            counter += 1
            print(counter)
            await asyncio.sleep_ms(100)

    def stop(self):
        self.run = 0
        print("should stop now")

async def main():
    test = Test()
    test.run_loop()
    print("looop started.. wait..")
    await asyncio.sleep(2)
    test.stop()

asyncio.run(main())

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

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