众所周知,python的多线程开发在GIL(全局器解释锁)下饱受诟病,在单核模式下搞多线程对效率的提升相当有限。于是大家的共识就是搞io密集的程序,建议采用多线程,计算密集型的程序就搞多进程。近期的一些开发经历,让我大量尝试采用多进程和异步io的方式来提高效率。
  一.采用多进程。
  1.用过multiprocessing.process和queue及pool,但是一直有报错,位置在multiprocessing.spawn的_main(fd,parent_sentinel)中reduction.pickle.load(from_parent)。网上提供了各种诸如修改权限,修改reduction协议类型的方案,始终未能解决。最后竟然是更新了python版本后不药而愈,但最后放弃了这种方式。
  2.使用concurrent.futures.ProcessPoolExecutor,官方文档很详细。程序运行也很不错,但是在脚本执行完毕后退出时抛出异常。Error in atexit._run_exitfuncs。大致的内容是handle is closed,通过追踪大致可以判断出脚本执行完毕时,会有futures.process的_python_exit()执行,此时ProcessPoolExecutor执行完毕后释放,没有线程可以被wakeup,所以报错。引起这个问题的是官方推荐的with as写法,with as 执行完毕后会将对象释放,结果在退出的时候引发异常。
  解决方案也很反常,不使用with as的自动释放,也不使用shutdown手动释放,而是不释放,在整个脚本执行完毕的时候,由_python_exit()进行释放。
  有意思的是concurrent.futures.process文档里有这么一段注释,可以自行研究。
# Workers are created as daemon threads and processes. This is done to allow the
# interpreter to exit when there are still idle processes in a
# ProcessPoolExecutor's process pool (i.e. shutdown() was not called). However,
# allowing workers to die with the interpreter has two undesirable properties:
# - The workers would still be running during interpreter shutdown,
# meaning that they would fail in unpredictable ways.
# - The workers could be killed while evaluating a work item, which could
# be bad if the callable being evaluated has external side-effects e.g.
# writing to a file.
#
# To work around this problem, an exit handler is installed which tells the
# workers to exit when their work queues are empty and then waits until the
# threads/processes finish.
  二.采用异步io。
  python在3.4中有了asyncio。官方给的示例可以看出来这是个消息循环,eventloop是在当前的上下文中提供的,而且可以和协程一起执行。最新的文档里可以看到eventloop已经不再只是同协程一起提供异步了。
  我们可以将多个耗时的任务进行封装,丢进eventloop中,当线程执行到需要等待的操作如io,主线程不会等待,而是切换执行到下一个可执行任务,因此可以实现并发执行。
  三.多进程和异步io结合。
  经过尝试多线程中没有找到使用异步io的方式,因为eventloop是从当前上下文中提供的,也就是主线程。于是换了个思路,使用多进程,让每个进程的‘主线程’通过异步io来实现并发,经多次尝试后这种方案是可行的。
  因为同时运行的进程数量上限是受cpu内核数量的上限影响的,一般的建议是不超过内核数量,但是在一些场景的限制下为了提高效率,单纯受限的多进程不能满足要求的时候,不妨将多进程的‘主进程’结合并发来提高效率。
  由于没有实际测试性能,不能断言究竟哪种方式效率更高,毕竟也与任务内容有关。这只是一种思路,留待日后验证。
  代码如下:
import asyncio
import aiohttp
from concurrent.futures import ProcessPoolExecutor, as_completed ,ThreadPoolExecutor
import time async def post_http():
# 示例
url = ''
data = ''
async with aiohttp.ClientSession() as session:
async with session.post(url=url, data=data, headers={}, timeout=60) as resp:
r_json = await resp.json()
return r_json async def t_handler(data, t_flag, p_flag, semaphore):
async with semaphore:
for d in data:
print(f'pid:{p_flag} tid:{t_flag} data:{d}')
await asyncio.sleep(1) # 处理费时的io操作,比如httprequest
return def p_handler(datas, p_flag):
# 线程并发数需要有限制 linux打开文件最大默认为1024 win为509 待确认
ts = time.time()
num = 10 # 最大并发数
count = len(datas)
block = int(count / num) + 1
tar_datas = [datas[i * block: (i + 1) * block if (i + 1) * block < count else count] for i in range(num)]
semaphore = asyncio.Semaphore(num)
tasks = [t_handler(d, i, p_flag, semaphore) for i, d in enumerate(tar_datas)] loop = asyncio.get_event_loop() # 基于当前线程 ,故在多线程中无法使用 只能在多进程中使用
loop.run_until_complete(asyncio.wait(tasks))
loop.close() return f'\033[0;32mprocess {p_flag} :cost {time.time() - ts}\033[0m' if __name__ == '__main__':
ts = time.time()
datas = [i for i in range(1000)]
datas = [datas[i * 100:(i + 1) * 100] for i in range(10)] # 每个进程要处理的数据 # 启动异步io 主线程调用 event_loop 在当前线程下启动异步io 实现并发
# res = p_handler(datas,1)
# print(res) p_num = 10
block_len = 100 datas = [datas[i * 100:(i + 1) * 100] for i in range(p_num)] # 每个进程要处理的数据
# ProcessPoolExecutor 可能与运行环境有关 官方的 with as 会主动释放线程 导致主线程退出时找不到进程池内进程已经被释放 导致Error in atexit._run_exitfuncs异常
executor = ProcessPoolExecutor(p_num)
futures = [executor.submit(p_handler, d, p_flag) for p_flag, d in enumerate(datas)]
for f in as_completed(futures):
if f.done():
res = f.result()
print(res) print(f'Exit!! cost:{time.time() - ts}')

  

python 多进程和异步io的有机结合 Error in atexit._run_exitfuncs的更多相关文章

  1. [译]Python中的异步IO:一个完整的演练

    原文:Async IO in Python: A Complete Walkthrough 原文作者: Brad Solomon 原文发布时间:2019年1月16日 翻译:Tacey Wong 翻译时 ...

  2. python之爬虫_并发(串行、多线程、多进程、异步IO)

    并发 在编写爬虫时,性能的消耗主要在IO请求中,当单进程单线程模式下请求URL时必然会引起等待,从而使得请求整体变慢 import requests def fetch_async(url): res ...

  3. 使用Python实现多线程、多进程、异步IO的socket通信

    多线程实现socket通信服务器端代码 import socket import threading class MyServer(object): def __init__(self): # 初始化 ...

  4. 【Python】【异步IO】

    # [[异步IO]] # [协程] '''协程,又称微线程,纤程.英文名Coroutine. 协程的概念很早就提出来了,但直到最近几年才在某些语言(如Lua)中得到广泛应用. 子程序,或者称为函数,在 ...

  5. 爬虫之多线程 多进程 自定义异步IO框架

    什么是进程? 进程是程序运行的实例,是系统进行资源分配和调度的一个独立单位,它包括独立的地址空间,资源以及1个或多个线程. 什么是线程? 线程可以看成是轻量级的进程,是CPU调度和分派的基本单位. 进 ...

  6. 多线程,多进程和异步IO

    1.多线程网络IO请求: #!/usr/bin/python #coding:utf-8 from concurrent.futures import ThreadPoolExecutor impor ...

  7. python 并发编程 异步IO模型

    异步IO(Asynchronous I/O) Linux下的asynchronous IO其实用得不多,从内核2.6版本才开始引入.先看一下它的流程: 用户进程发起read操作之后,立刻就可以开始去做 ...

  8. Python 并发总结,多线程,多进程,异步IO

    1 测量函数运行时间 import time def profile(func): def wrapper(*args, **kwargs): import time start = time.tim ...

  9. Python 协程/异步IO/Select\Poll\Epoll异步IO与事件驱动

    1 Gevent 协程 协程,又称微线程,纤程.英文名Coroutine.一句话说明什么是线程:协程是一种用户态的轻量级线程. 协程拥有自己的寄存器上下文和栈.协程调度切换时,将寄存器上下文和栈保存到 ...

  10. Python 事件驱动与异步IO

    一.事件驱动编程是一种编程范式,这里程序的执行流由外部事件来决定.它的特点是包含一个事件循环,当外部事件发生时使用回调机制来出发相应的处理.另外两种常见的编程范式是(单线程)同步以及多线程编程. 1. ...

随机推荐

  1. A. Greatest Convex【Codeforces Round #842 (Div. 2)】

    A. Greatest Convex You are given an integer \(k\). Find the largest integer \(x\), where \(1≤x<k\ ...

  2. [Untiy]贪吃蛇大作战(五)——游戏主界面

    接着上一节: 4.AI蛇的设计 这里AI蛇大部分代码都可以参照主角的代码,我这里的实现其实还可以进行改进.基本原理就是蛇创建之后给蛇一个随机方向的单位向量,AI蛇的蛇头添加一个比蛇头大两三倍大小的碰撞 ...

  3. windows使用管理员权限安装软件

    安装步骤 系统搜索 cmd 点击右键,使用管理者方式运行 输入用户名密码 成功以管理员身份运行 cd 到软件存储的目录 输入软件执行文件名, 按回车键,成功开始安装

  4. golang主协程等待子协程执行完毕

    无限等待 计时等待 channel通信 select 等待组

  5. Node.js学习笔记----day04之学生信息管理系统

    认真学习,认真记录,每天都要有进步呀!!! 加油叭!!! 一.起步 项目结构 安装需要的包 初始化显示index.html index.html var express = require('expr ...

  6. 【一句话】Java8后abstract class和interface的区别

    首先一句话: Java8后(1)interface支持default和static方法有实现,abstract class依然是抽象方法和非抽象方法,(2)可同时实现多个interface,(3)但成 ...

  7. Dijkstra求最短路 I(朴素算法)

    这道题目又是一个新算法,名叫Dijkstra 主要思路是:输入+dist和vis初始化(都初始化为0x3f)+输入g(邻接矩阵)+Dijkstra函数       Dijkstra函数:先将dist[ ...

  8. JAVA虚拟机05-内存溢出示例(jdk1.8)

    1.JAVA虚拟机堆内存溢出OutOfMemoryError 1.1设置参数 -Xms20m -Xmx20m -XX:+HeapDumpOnOutOfMemoryError 最小堆的大小20m 最大堆 ...

  9. 你好 ChatGPT, 帮我看下这段代码有什么问题?

    点赞再看,动力无限. 微信搜「程序猿阿朗 」. 本文 Github.com/niumoo/JavaNotes 和 未读代码博客 已经收录,有很多系列文章. 今天一个很简单的功能,触发了一个 BUG,处 ...

  10. Ubuntu18.4安装g2o

    1.安装依赖项: sudo apt-get install cmake libeigen3-dev libsuitesparse-dev qtdeclarative5-dev qt5-qmake li ...