关于异步IO asyncIO 协程coroutine 并发的疑惑。

问题在最下面!

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import threading, asyncio, time

@asyncio.coroutine
def sleep1():     
    print("Am I being executed concurrently?")
    #yield from asyncio.sleep(3)
    time.sleep(1)     
    yield

@asyncio.coroutine
def hello(n):

    print(n,'Hello world! (%s)' % threading.currentThread())
    yield from sleep1()
    print(n,'Hello again! (%s)' % threading.currentThread())

loop = asyncio.get_event_loop()                 # 获得时间循环
tasks = [hello(n) for n in range(1,5)]          # 布置任务
loop.run_until_complete(asyncio.wait(tasks))    # 开始执行
loop.close()

输出结果:

2 Hello world! (<_MainThread(MainThread, started 13608)>)
Am I being executed concurrently?
1 Hello world! (<_MainThread(MainThread, started 13608)>)
Am I being executed concurrently?
3 Hello world! (<_MainThread(MainThread, started 13608)>)
Am I being executed concurrently?
4 Hello world! (<_MainThread(MainThread, started 13608)>)
Am I being executed concurrently?
2 Hello again! (<_MainThread(MainThread, started 13608)>)
1 Hello again! (<_MainThread(MainThread, started 13608)>)
3 Hello again! (<_MainThread(MainThread, started 13608)>)
4 Hello again! (<_MainThread(MainThread, started 13608)>)

问题:4个协程hello的:hello world! 为什么没有并发输出? 而是等了 sleep1() ?

重新补充:
我清楚 time.sleep 无法异步,只能串行。这个没有问题。
但是 yield from sleep1(),遇到 yield 按照协程的规则,当前协程等待 sleep1()返回,但控制权应该交给其他协程继续运行啊??
我期待的结果是 4个hello world 迅速输出然后 阻塞的 sleep 依次等待。然后 4个 hello again 输出。这也是串行的,单线程。应该符合协程的规则。

阅读 3.6k
3 个回答

time.sleep改成asyncio.sleep

你既然用了asyncio这个框架,就要按照这个框架作者的说明去使用,不能直接使用sleep,那样会在主程序直接全局sleep。

我很奇怪为什么你这里输出为什么不是1,2,3,4而是2,1,3,4...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题