asyncio简单入门(一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a19990412/article/details/81913511

前述

廖老师的python教程 看到了这些东西,学习了一下。

内容

代码:

import threading
import asyncio


@asyncio.coroutine
def hello(t):
    print('Hello world! (%s) %d' % (threading.currentThread(), t))
    yield from asyncio.sleep(1)
    print('Hello again! (%s) %d' % (threading.currentThread(), t))


loop = asyncio.get_event_loop()
tasks = [hello(1), hello(2)]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

输入的结果

Hello world! (<_MainThread(MainThread, started 9688)>) 1
Hello world! (<_MainThread(MainThread, started 9688)>) 2
Hello again! (<_MainThread(MainThread, started 9688)>) 1
Hello again! (<_MainThread(MainThread, started 9688)>) 2

(注意:中间那停了一秒! 只停了一秒)

说明,还是一个线程。 但是确实实现了异步的过程。(对于廖老师代码做了一些修改给出的)

代码解释:

这里的 yield from 其实非常形象(果然写python就是在写英语)。就是表示在这里的这个语句中yield出来。

然后寻找其他可以执行的。

代码二:

async def hello():
    print("Hello world!")
    r = await asyncio.sleep(1)
    print("Hello again!")

这个代码块,等价于

@asyncio.coroutine
def hello():
    print("Hello world!")
    r = yield from asyncio.sleep(1)
    print("Hello again!")

猜你喜欢

转载自blog.csdn.net/a19990412/article/details/81913511