python 中的asyncio和await

参考:https://www.liaoxuefeng.com/wiki/1016959663602400/1017970488768640

以下所有内容都是个人理解:

1、几个名词

asyn:异步  await:等待

2、协程

协程,跟线程一样,有一些库能够方便的支持我们使用,,能够遇到耗时的操作的时候,自动帮我们切换到别的协程当中去

3、举例子1

同一个线程号,因此,相当于一段程序

import threading
import asyncio

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

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


运行结果:
Hello world! (<_MainThread(MainThread, started 18860)>)
Hello world! (<_MainThread(MainThread, started 18860)>)
Hello again! (<_MainThread(MainThread, started 18860)>)
Hello again! (<_MainThread(MainThread, started 18860)>)

4、举例子2async/await

只替换了两个地方:

  1. @asyncio.coroutine替换为async
  2. yield from替换为await
import threading
import asyncio

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


async def hello():
    print("Hello world!")
    r = await asyncio.sleep(1)
    print("Hello again!")
loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()


运行结果

Hello world!
Hello world!
Hello again!
Hello again!

5、关于后半部分的说明

 

建立一个程序:

loop = asyncio.get_event_loop()

添加需要切换的执行的协程g:

tasks = [hello(), hello()]

开始运行这些协程

loop.run_until_complete(asyncio.wait(tasks))

回收资源:

loop.close()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

没有水杯和雨伞的工科男

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值