Python 异步协程函数原理及实例详解

yipeiwu_com5年前Python基础

这篇文章主要介绍了Python 异步协程函数原理及实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

一、 asyncio

1.python3.4开始引入标准库之中,内置对异步io的支持

2.asyncio本身是一个消息循环

3.步骤:

(1)创建消息循环

(2)把协程导入

(3)关闭

4.举例:

import threading
# 引入异步io包
import asyncio
# 使用协程
@ asyncio.coroutine
def hello():
	print("Hello World!(%s)" % threading.current_thread())
print("Start......(%s)" % threading.current_thread())
yield from asyncio.sleep(5)
print("Done.....(%s)" % threading.current_thread())
print("Hello again!(%s)" % threading.current_thread())
# 启动消息循环
loop = asyncio.get_event_loop()
# 定义任务
tasks = [hello(), hello()]
# asyncio使用wait等待task执行完毕
loop.run_until_complete(asyncio.wait(
	tasks))
# 关闭消息循环
loop.close()

二、asyncio and await

1.为了更好的表示异步io

2.python3.5引入

3.让协程代码更加简洁

4.使用上,可以简单的进行替换

(1)用async来替换@asyncio,coroutine

(2)用await来替换yield from

按照上面这个语法可以来改写前面的例子,运行结果是完全一致的

三、aiohttp

1.asyncio实现单线程的并发io,在客户端用处不大

2.在服务端可以asyncio+coroutine配合,因为http是io操作

3.asyncio实现了tcp,udp,ssl等协议

4.aiohttp是基于asyncio实现的http框架

5.例子:

import asyncio
from aiohttp
import web
​
async def index(request):
	await asyncio.sleep(0.5)
return web.Response(body = b "<h1>Index</h1>")
​
async def hello(request):
	await asyncio.sleep(0.5)
text = "<h1>hello,%s!</h1>" % request.match_info[
	"name"]
return web.Response(body = text.encode(
	"utf-8"))
​
async def init(loop):
	app = web.Application(loop = loop)
app.router.add_route("GET", "/", index)
app.router.add_route("GET",
	"/hellp/{name}", hello)
srv = await loop.create_server(app.make_handler(),
	"127.0.0.1", 8000)
print(
	"Server started at http://127.0.0.1:8000..."
)
return srv
​
loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()

四、current,futures

1. python3新增的库

2.类似其它语言的线程池的概念

3.利用multiprocessing实现真正的并行计算(当然要求我们的CPU是多核的)

4.核心原理:以子进程的形式,实现多个python解释器

从而令python程序,可以利用多核CPU来提升执行速度。由于子进程于主解释器相分离,所以他们的全局解释器锁也是相互独立的,每个子进程都能完整的使用一个CPU内核

5.concurrent.futures.Executor

(1)ThreadPoolExecutor

(2)ProcessPoolExecutor

(3)执行的时候需要自行选择

(4)submit(fn,args,kwargs)

fn:异步执行的函数

args,kwargs参数

import time
from concurrent.futures
import ThreadPoolExecutor
​
def return_future(msg):
	time.sleep(3)
return msg
​
# 创建一个线程池
pool = ThreadPoolExecutor(max_workers =
	2)# 参数是2, 代表里面有两个线程干活
# 往线程池里面加入两个task
f1 = pool.submit(return_future, "hello")
f2 = pool.submit(return_future, "world")
time.sleep(1)
# 等待执行完毕
print(f1.done())
time.sleep(3)
print(f2.done())
# 结果
print(f1.result())
print(f2.result())

源码

d28_1_asynchronization_examples.py

https://github.com/ruigege66/Python_learning/blob/master/d28_1_asynchronization_examples.py

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现Mysql数据统计及numpy统计函数

Python实现Mysql数据统计的实例代码如下所示: import pymysql import xlwt excel=xlwt.Workbook(encoding='utf-8'...

在Django的form中使用CSS进行设计的方法

修改form的显示的最快捷的方式是使用CSS。 尤其是错误列表,可以增强视觉效果。自动生成的错误列表精确的使用`` <ul class=”errorlist”>``,这样,我...

PyCharm代码回滚,恢复历史版本的解决方法

PyCharm代码回滚,恢复历史版本的解决方法

当我们修改一份代码的时候,也许会碰到修改后的代码还不如修改之前的代码能够满足自己的需求,那么这个时候我们就需要对代码进行回滚,下面我们来看一下在PyCharm里面如何操作。 首先在我们需...

python中字符串内置函数的用法总结

capitalize() 首字母大写 a='someword' b=a.capitalize() print(b) —>Someword casefold()&l...

Python标准库defaultdict模块使用示例

Python标准库中collections对集合类型的数据结构进行了很多拓展操作,这些操作在我们使用集合的时候会带来很多的便利,多看看很有好处。 defaultdict是其中一个方法,就...