当前位置:
首页 > 编程开发 > Python基础教程 >
-
python基础教程之【2020Python修炼记】python并发编程(七)协程
本站最新发布 Python从入门到精通|Python基础教程
试听地址 https://www.xin3721.com/eschool/pythonxin3721/
试听地址 https://www.xin3721.com/eschool/pythonxin3721/
一、什么是协程
引例:
import time # 串行执行计算密集型的任务 1.2372429370880127 def func1(): for i in range(10000000): i + 1 def func2(): for i in range(10000000): i + 1 start_time = time.time() func1() func2() print(time.time() - start_time) 切换 + yield 2.1247239112854004 import time def func1(): while True: 10000000 + 1 yield def func2(): g = func1() # 先初始化出生成器 for i in range(10000000): i + 1 next(g) start_time = time.time() func2() print(time.time() - start_time)
1、协程:
# 单线程实现并发,在应用程序里控制多个任务的切换+保存状态
# 优点:应用程序级别速度要远远高于操作系统的切换
# 缺点:
多个任务一旦有一个阻塞没有切,整个线程都阻塞在原地,该线程内的其他的任务都不能执行了
一旦引入协程,就需要检测单线程下所有的IO行为, 实现遇到IO就切换,少一个都不行,
以为一旦一个任务阻塞了,整个线程就阻塞了, 其他的任务即便是可以计算,但是也无法运行了
2、协程序的目的: 想要在单线程下实现并发 并发指的是多个任务看起来是同时运行的 并发=切换+保存状态
二、gevent模块-应用举例:
from gevent import monkey;monkey.patch_all() import time from gevent import spawn """ gevent模块本身无法检测常见的一些io操作 在使用的时候需要你额外的导入一句话 from gevent import monkey monkey.patch_all() 又由于上面的两句话在使用gevent模块的时候是肯定要导入的 所以还支持简写 from gevent import monkey;monkey.patch_all() """ def heng(): print('哼') time.sleep(2) print('哼') def ha(): print('哈') time.sleep(3) print('哈') def heiheihei(): print('heiheihei') time.sleep(5) print('heiheihei') start_time = time.time() g1 = spawn(heng) g2 = spawn(ha) g3 = spawn(heiheihei) g1.join() g2.join() # 等待被检测的任务执行完毕 再往后继续执行 g3.join() # heng() # ha() # print(time.time() - start_time) # 5.005702018737793 print(time.time() - start_time) # 3.004199981689453 5.005439043045044
三、协程实现TCP服务端并发
from gevent import monkey;monkey.patch_all() import socket from gevent import spawn def communication(conn): while True: try: data = conn.recv(1024) if len(data) == 0: break conn.send(data.upper()) except ConnectionResetError as e: print(e) break conn.close() def server(ip, port): server = socket.socket() server.bind((ip, port)) server.listen(5) while True: conn, addr = server.accept() spawn(communication, conn) if __name__ == '__main__': g1 = spawn(server, '127.0.0.1', 8080) g1.join()
栏目列表
最新更新
如何使用OS模块中的stat方法
Python os 模块
seek() 方法
python打开文件实例1
Python写入文件
什么是流?
文件操作如何进制逐行读取
Python相对路径
with创建临时运行环境
Python文件操作
.Net Standard(.Net Core)实现获取配置信息
Linux PXE + Kickstart 自动装机
Shell 编程 基础
Shell 编程 条件语句
CentOS8-网卡配置及详解
Linux中LVM逻辑卷管理
1.数码相框-相框框架分析(1)
Ubuntu armhf 版本国内源
Linux中raid磁盘阵列
搭建简易网站
access教程之Access简介
mysql 安装了最新版本8.x版本后的报错:
Mysql空间数据&空间索引(spatial)
如何远程连接SQL Server数据库的图文教程
复制SqlServer数据库的方法
搜索sql语句
sql中返回参数的值
sql中生成查询的模糊匹配字符串
数据定义功能
数据操作功能