吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 247|回复: 4
收起左侧

[求助] 关于异步并发控制的问题

[复制链接]
sweetarea 发表于 2024-3-15 11:33
大家好,我再学习python异步编程中,遇到一个无法理解的情况,代码如下:
import asyncio
import time

async def do():
    for i in range(0,10):
        asyncio.create_task(say_after(1,i))

async def say_after(delay, what):
    print(f'say_after_delay:{delay}')
    await asyncio.sleep(delay)
    print(f'say_after:{what}')
    return f'返回值:{what}'

async def main():
    print(f"started at {time.strftime('%X')}")

    await do()
    flag = True
    while flag:
        for i in asyncio.all_tasks():
            print(i.get_name())
        # await asyncio.sleep(1)
        time.sleep(1)
    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

当使用time.sleep(1)的时候,控制台不会打印say_after的执行内容。知道time.sleep会阻塞线程,但是问题是无线循环时为什么控制流为什么一直不会执行到异步任务了?


发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

bushixian 发表于 2024-3-15 11:50
await sleep是当前线程sleep
whh19921024 发表于 2024-3-15 12:09
 楼主| sweetarea 发表于 2024-3-15 12:19
whh19921024 发表于 2024-3-15 12:09
你的flag一直是true,都出不去吧

是的,因为没有直接对task进行await,没有无限循环运行就直接运行了。
shoutoutuoadi 发表于 2024-3-15 15:02
线程出了点问题
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止回复与主题无关非技术内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-1 06:03

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表