一、  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

2.CSDN:https://blog.csdn.net/weixin_44630050(心悦君兮君不知-睿)

3.博客园:https://www.cnblogs.com/ruigege0000/

4.欢迎关注微信公众号:傅里叶变换,个人公众号,仅用于学习交流,后台回复”礼包“,获取大数据学习资料

Python连载42-异步协程函数的更多相关文章

  1. Python爬虫进阶 | 异步协程

    一.背景 之前爬虫使用的是requests+多线程/多进程,后来随着前几天的深入了解,才发现,对于爬虫来说,真正的瓶颈并不是CPU的处理速度,而是对于网页抓取时候的往返时间,因为如果采用request ...

  2. python爬虫--多任务异步协程, 快点,在快点......

    多任务异步协程asyncio 特殊函数: - 就是async关键字修饰的一个函数的定义 - 特殊之处: - 特殊函数被调用后会返回一个协程对象 - 特殊函数调用后内部的程序语句没有被立即执行 - 协程 ...

  3. python tornado TCPserver异步协程实例

    项目所用知识点 tornado socket tcpserver 协程 异步 tornado tcpserver源码抛析 在tornado的tcpserver文件中,实现了TCPServer这个类,他 ...

  4. python(18)- 协程函数及应用

    协程 def init(func): def wrapper(*args,**kwargs): obj = func(*args,**kwargs) next(obj) return obj retu ...

  5. Python 简易的异步协程使用方法

    代码 import asyncio async def ex(id, n): print(id+" start") await asyncio.sleep(n/2) print(i ...

  6. python——asyncio模块实现协程、异步编程

    我们都知道,现在的服务器开发对于IO调度的优先级控制权已经不再依靠系统,都希望采用协程的方式实现高效的并发任务,如js.lua等在异步协程方面都做的很强大. Python在3.4版本也加入了协程的概念 ...

  7. 消息/事件, 同步/异步/协程, 并发/并行 协程与状态机 ——从python asyncio引发的集中学习

    我比较笨,只看用await asyncio.sleep(x)实现的例子,看再多,也还是不会. 已经在unity3d里用过coroutine了,也知道是“你执行一下,主动让出权限:我执行一下,主动让出权 ...

  8. python协程函数应用 列表生成式 生成器表达式

    协程函数应用 列表生成式 生成器表达式   一.知识点整理: 1.可迭代的:对象下有_iter_方法的都是可迭代的对象 迭代器:对象._iter_()得到的结果就是迭代器 迭代器的特性: 迭代器._n ...

  9. python爬虫---单线程+多任务的异步协程,selenium爬虫模块的使用

    python爬虫---单线程+多任务的异步协程,selenium爬虫模块的使用 一丶单线程+多任务的异步协程 特殊函数 # 如果一个函数的定义被async修饰后,则该函数就是一个特殊的函数 async ...

随机推荐

  1. Assets.xcassets:-1: Failed to find a suitable device for the type IBSimDeviceTypeiPad2x

    Assets.xcassets:-1: Failed to find a suitable device for the type IBSimDeviceTypeiPad2x 不知道assets发生了 ...

  2. 2、netty第一个例子,简单的http服务器

    用netty来启动一个简单的可处理http请求的服务器. 依照前面写的使用netty的过程.贴上代码 server import io.netty.bootstrap.ServerBootstrap; ...

  3. 【Java基础】接口和抽象类之间的对比

    Java 中的接口和抽象类之间的对比 一.接口 Interface,将其翻译成插座可能就更好理解了.我们通常利用接口来定义实现类的行为,当你将插座上连接笔记本的三角插头拔掉,换成微波炉插上去的时候,你 ...

  4. centos7.6 jumpserver 堡垒机 重启启动顺序

    cd /sdata/usr/local python3. -m venv py3 source /sdata/usr/local/py3/bin/activate cd /sdata/usr/loca ...

  5. 005.SQLServer AlwaysOn可用性组高可用简介

    一 AlwaysOn 可用性组 1.1 AlwaysOn 可用性组概述 AlwaysOn 可用性组功能是一个提供替代数据库镜像的企业级方案的高可用性和灾难恢复解决方案.SQL Server 2012 ...

  6. 经验之谈-switch结构常见错误的分析与处理

    1.缺少break语句 本来只想输出“出任武林盟主”可输出结果为 错误分析:在 switch结构中,每一个case语句块后面如果不写 break语句, switch就会 直接往下面的case语句块运行 ...

  7. workerman连接失败方法

    workerman链接失败方法 1 防火墙关闭 2 端口开启 3 改成websocket协议

  8. Java题库——Chapter12 异常处理和文本IO

    异常处理 1)What is displayed on the console when running the following program? class Test { public stat ...

  9. JS 实现

    JavaScript 使用 HTML 中的脚本必须位于<script> 与 </script>标签之间. 脚本可被放置在 HTML 页面的 <body>和 < ...

  10. 微信小程序支付功能 C# .NET开发

    微信小程序支付功能的开发的时候坑比较多,不过对于钱的事谨慎也是好事.网上关于小程序支付的实例很多,但是大多多少有些问题,C#开发的更少.此篇文档的目的是讲开发过程中遇到的问题做一个备注,也方便其他开发 ...