在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python  網(wǎng)絡(luò)安全/ 關(guān)于異步IO asyncIO 協(xié)程coroutine 并發(fā)的疑惑。

關(guān)于異步IO asyncIO 協(xié)程coroutine 并發(fā)的疑惑。

問題在最下面!

#!/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()                 # 獲得時(shí)間循環(huán)
tasks = [hello(n) for n in range(1,5)]          # 布置任務(wù)
loop.run_until_complete(asyncio.wait(tasks))    # 開始執(zhí)行
loop.close()

輸出結(jié)果:

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個(gè)協(xié)程hello的:hello world! 為什么沒有并發(fā)輸出? 而是等了 sleep1() ?

重新補(bǔ)充:
我清楚 time.sleep 無法異步,只能串行。這個(gè)沒有問題。
但是 yield from sleep1(),遇到 yield 按照協(xié)程的規(guī)則,當(dāng)前協(xié)程等待 sleep1()返回,但控制權(quán)應(yīng)該交給其他協(xié)程繼續(xù)運(yùn)行?。??
我期待的結(jié)果是 4個(gè)hello world 迅速輸出然后 阻塞的 sleep 依次等待。然后 4個(gè) hello again 輸出。這也是串行的,單線程。應(yīng)該符合協(xié)程的規(guī)則。

回答
編輯回答
青裙

time.sleep改成asyncio.sleep

2018年4月21日 06:31
編輯回答
萌小萌

你既然用了asyncio這個(gè)框架,就要按照這個(gè)框架作者的說明去使用,不能直接使用sleep,那樣會在主程序直接全局sleep。

2017年8月8日 13:22
編輯回答
凝雅

我很奇怪為什么你這里輸出為什么不是1,2,3,4而是2,1,3,4...

2018年6月30日 03:07