账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    关于协程coroutine的执行顺序问题
    67
    0
    import threading
    import asyncio
    import time
    
    @asyncio.coroutine
    def hello(n):
        print("-----")
        time.sleep(3)
        print("======")
        print(n,'Hello world! (%s)' % threading.currentThread())
        yield from asyncio.sleep(1) # 异步调用asyncio.sleep(1):  
        print(n,'Hello again! (%s)' % threading.currentThread())
    
    loop = asyncio.get_event_loop()  # 获取EventLoop:
    h1 = hello(1)
    h2 = hello(2)
    tasks = [h1,h2]
    loop.run_until_complete(asyncio.wait(tasks)) # 执行coroutine
    loop.close()
    

    运行结果:

    -----
    ======
    2 Hello world! (<_MainThread(MainThread, started 4328)>)
    -----
    ======
    1 Hello world! (<_MainThread(MainThread, started 4328)>)
    2 Hello again! (<_MainThread(MainThread, started 4328)>)
    1 Hello again! (<_MainThread(MainThread, started 4328)>)

    问题: 为什么 2 hello world 先被输出了??

    1
    打赏
    收藏
    点击回答
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部