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

作者:心悦君兮君不知-睿 时间:2022-05-26 11:29:55 

这篇文章主要介绍了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()

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

二、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())

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

源码

d28_1_asynchronization_examples.py

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

来源:https://www.cnblogs.com/ruigege0000/p/11682120.html

标签:python,异步,协程,函数
0
投稿

猜你喜欢

  • python 对txt中每行内容进行批量替换的方法

    2022-12-29 21:37:45
  • python面向对象版学生信息管理系统

    2022-07-23 02:16:57
  • 使用Python从有道词典网页获取单词翻译

    2022-12-10 21:18:03
  • django中ImageField的使用详解

    2023-09-28 03:58:37
  • asp 得到动态数组中元素的个数

    2011-03-30 10:55:00
  • Python面向对象思想与应用入门教程【类与对象】

    2022-05-18 23:19:06
  • php编程每天必学之表单验证

    2023-07-19 05:50:59
  • PHP实现将浏览历史页面网址保存到cookie的方法

    2023-08-16 05:25:29
  • asp 判断上传文件中是否存在危险代码

    2011-03-17 11:19:00
  • MySQL分页优化解析

    2008-12-22 14:56:00
  • Python编写百度贴吧的简单爬虫

    2023-12-06 02:17:56
  • Python入门篇之正则表达式

    2021-10-20 09:01:34
  • 开启Django博客的RSS功能的实现方法

    2022-06-16 02:02:04
  • OpenCV imread读取图片失败的问题及解决

    2021-10-20 06:44:00
  • python中如何实现将数据分成训练集与测试集的方法

    2022-10-03 23:11:45
  • PHP函数篇详解十进制、二进制、八进制和十六进制转换函数说明

    2023-11-24 06:26:11
  • Matplotlib 绘制饼图解决文字重叠的方法

    2023-06-12 22:23:06
  • javascript面向对象编程(三)

    2008-03-07 13:19:00
  • Softmax函数原理及Python实现过程解析

    2022-12-15 02:18:24
  • 一个统计当前在线用户的解决方案

    2007-10-13 19:27:00
  • asp之家 网络编程 m.aspxhome.com