首页 > 系统相关 >python基础-进程池、submit同异步调用、shutdown参数、ProcessPoolExecutor进程池、进程池ftp

python基础-进程池、submit同异步调用、shutdown参数、ProcessPoolExecutor进程池、进程池ftp

时间:2023-05-21 12:55:06浏览次数:48  
标签:__ ProcessPoolExecutor name python print time 进程

转载:(14条消息) python基础-进程池、submit同异步调用、shutdown参数、ProcessPoolExecutor进程池、进程池ftp_python submit_易辰_的博客-CSDN博客

引入进程池

在学习线程池之前,我们先看一个例子

from multiprocessing import  Process
import  time
def task(name):
    print("name",name)
    time.sleep(1)

if __name__ == "__main__":
    start = time.time()
    p1 = Process(target=task,args=("safly1",))
    p2 = Process(target=task, args=("safly2",))
    p3 = Process(target=task, args=("safly3",))

    p1.start()
    p2.start()
    p3.start()

    p1.join()
    p2.join()
    p3.join()

    print("main")

    end = time.time()
    print(end- start)

输出如下:

name safly1
name safly2
name safly3
main
1.2071197032928467

以上的方式是一个个创建进程,这样的耗费时间才1秒多,虽然高效,但是有什么弊端呢?
如果并发很大的话,会给服务器带来很大的压力,所以引入了进程池的概念

使用ProcessPoolExecutor进程池
Python3.2开始,标准库为我们提供了concurrent.futures模块,它提供了ThreadPoolExecutor和ProcessPoolExecutor两个类,实现了对threading和multiprocessing的进一步抽象,对编写线程池/进程池提供了直接的支持。

通过ProcessPoolExecutor 来做示例。
我们来看一个最简单的进程池

from concurrent.futures import ProcessPoolExecutor
import  time
def task(name):
    print("name",name)
    time.sleep(1)

if __name__ == "__main__":
    start = time.time()
    ex = ProcessPoolExecutor(2)

    for i in range(5):
        ex.submit(task,"safly%d"%i)
    ex.shutdown(wait=True)

    print("main")
    end = time.time()
    print(end - start)

输出如下:

E:\python\python_sdk\python.exe "E:/python/py_pro/4 进程池.py"
name safly0
name safly1
name safly2
name safly3
name safly4
main
3.212218999862671

简单解释下:
ProcessPoolExecutor(2)创建一个进程池,容量为2,循环submit出5个进程,然后就在线程池队列里面,执行多个进程,ex.shutdown(wait=True)意思是进程都执行完毕,在执行主进程的内容

使用shutdown

ex.shutdown(wait=True)是进程池内部的进程都执行完毕,才会关闭,然后执行后续代码
如果改成false呢?看如下代码

from concurrent.futures import ProcessPoolExecutor
import  time
def task(name):
    print("name",name)
    time.sleep(1)

if __name__ == "__main__":
    start = time.time()
    ex = ProcessPoolExecutor(2)

    for i in range(5):
        ex.submit(task,"safly%d"%i)
    ex.shutdown(wait=False)

    print("main")
    end = time.time()
    print(end - start)

输出如下:

main
0.01500844955444336
name safly0
name safly1
name safly2
name safly3
name safly4

使用submit同步调用

同步调用:提交/调用一个任务,然后就在原地等着,等到该任务执行完毕拿到结果,再执行下一行代码

from concurrent.futures import ProcessPoolExecutor
import time, random, os

def piao(name, n):
    print('%s is piaoing %s' % (name, os.getpid()))
    time.sleep(1)
    return n ** 2


if __name__ == '__main__':
    p = ProcessPoolExecutor(2)
    start = time.time()
    for i in range(5):
        res=p.submit(piao,'safly %s' %i,i).result() #同步调用
        print(res)

    p.shutdown(wait=True)
    print('主', os.getpid())

    stop = time.time()
    print(stop - start)

输出如下:

E:\python\python_sdk\python.exe "E:/python/py_pro/4 进程池.py"
safly 0 is piaoing 12996
0
safly 1 is piaoing 14044
1
safly 2 is piaoing 12996
4
safly 3 is piaoing 14044
9
safly 4 is piaoing 12996
16
主 12932
5.202786684036255

Process finished with exit code 0

使用submit异步调用

异步调用: 提交/调用一个任务,不在原地等着,直接执行下一行代码

# from multiprocessing import Process,Pool
from concurrent.futures import ProcessPoolExecutor
import time, random, os

def piao(name, n):
    print('%s is piaoing %s' % (name, os.getpid()))
    time.sleep(1)
    return n ** 2


if __name__ == '__main__':
    p = ProcessPoolExecutor(2)
    objs = []
    start = time.time()
    for i in range(5):
        obj = p.submit(piao, 'safly %s' % i, i)  # 异步调用
        objs.append(obj)

    p.shutdown(wait=True)
    print('主', os.getpid())
    for obj in objs:
        print(obj.result())

    stop = time.time()
    print(stop - start)

输出如下:

E:\python\python_sdk\python.exe "E:/python/py_pro/4 进程池.py"
safly 0 is piaoing 1548
safly 1 is piaoing 7872

safly 2 is piaoing 1548
safly 3 is piaoing 7872


safly 4 is piaoing 1548


主 7808
0
1
4
9
16
3.202626943588257

输出信息的换行是我标识有输出停顿的
简单说下执行流程:
由于进程池容量是容纳2个进程,所以会2+2+1 三次进入线程池执行,花费3秒

如果我们改下上面的代码,修改的代码如下:

from concurrent.futures import ProcessPoolExecutor
import time, random, os

def piao(name, n):
    print('%s is piaoing %s' % (name, os.getpid()))
    time.sleep(1)
    return n ** 2


if __name__ == '__main__':
    p = ProcessPoolExecutor(2)
    objs = []
    start = time.time()
    for i in range(5):
        obj = p.submit(piao, 'safly %s' % i, i)  # 异步调用
        objs.append(obj)

    for obj in objs:
        print(obj.result())


    p.shutdown(wait=True)
    print('主', os.getpid())


    stop = time.time()
    print(stop - start)

输出如下:(同样我用换行,标识出输出的时间段了)

E:\python\python_sdk\python.exe "E:/python/py_pro/4 进程池.py"
safly 0 is piaoing 7852
safly 1 is piaoing 8484


safly 2 is piaoing 7852
0
safly 3 is piaoing 8484
1



safly 4 is piaoing 7852
4
9


16
主 6816
3.178352117538452

进程池实现ftp

服务端:

from socket import *
from concurrent.futures import ProcessPoolExecutor
import os

server=socket(AF_INET,SOCK_STREAM)
server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
server.bind(('127.0.0.1',8080))
server.listen(5)

def talk(conn,client_addr):
    print('进程pid: %s' %os.getpid())
    while True:
        try:
            msg=conn.recv(1024)
            if not msg:break
            conn.send(msg.upper())
        except Exception:
            break

if __name__ == '__main__':
    p=ProcessPoolExecutor(5)
    while True:
        conn,client_addr=server.accept()
        p.submit(talk,conn,client_addr)

客户端:

from socket import *

client=socket(AF_INET,SOCK_STREAM)
client.connect(('127.0.0.1',8080))


while True:
    msg=input('>>: ').strip()
    if not msg:continue

    client.send(msg.encode('utf-8'))
    msg=client.recv(1024)
    print(msg.decode('utf-8'))

 

标签:__,ProcessPoolExecutor,name,python,print,time,进程
From: https://www.cnblogs.com/zhiminyu/p/17418465.html

相关文章

  • Python3.8多进程之共享内存
    转载:Python3.8多进程之共享内存-知乎(zhihu.com)最近发了个宏愿想写一个做企业金融研究的Python框架。拖出Python一看已经更新到了3.8,于是就发现了Python3.8里新出现的模块:multiprocessing.shared_memory。随手写了个测试。生成一个240MB大小的pandas.DataFrame,然后转换成nu......
  • python进程池ProcessPoolExecutor的用法与实现分析
    转载:(14条消息)【Python随笔】python进程池ProcessPoolExecutor的用法与实现分析_utmhikari的博客-CSDN博客concurrent.futures—Launchingparalleltasks—Python3.11.3documentation在python开发期间,由于GIL的原因,不能直接采用并行的方式处理代码逻辑。在multiprocess......
  • 使用Python进行nc数据转tiff(多图层)
    最近帮人处理了一批数据,发现matlab处理nc并不是很友好,遂查询了Python方法。参考文献:lhttp://www.dtmao.cc/news_show_498450.shtml#-*-coding:utf-8-*-#模块导入importnumpyasnpimportnetCDF4asncfromosgeoimportgdal,osr,ogrimportosimportglob#单个n......
  • Python高级编程技巧:函数式编程和闭包
    Python是一种非常流行的编程语言,可以用于各种应用领域,如Web开发,人工智能,数据科学等。其中,函数式编程和闭包是Python编程中非常重要的概念,本文将深入探讨这两个主题。函数式编程Python是一种多范式语言,既支持面向对象编程,也支持函数式编程。函数式编程的一大特点是强调函数的纯洁性......
  • Python的33个保留字有哪些?关键字大全
    Python的33个保留字包括False、None、True、and、as、assert等,Python的标准库提供了一个keyword模块,可以输出当前Python版本的所有关键字列表,腾讯云服务器网来详细说下Python的33个保留字及保留字查询方法:Python的33个保留字Python的保留字或关键字是指我们不能把它们用作任何标识......
  • Python计算目标检测中的IoU
    Python计算目标检测中的IoU前言前提条件相关介绍实验环境IoU概念代码实现前言本文是个人使用PythonPython处理文件的电子笔记,由于水平有限,难免出现错漏,敬请批评改正。更多精彩内容,可点击进入我的个人主页查看前提条件熟悉Python相关介绍Python是一种跨平台的计算机程序设计语言。......
  • Python操作常用数据库
    Python操作常用数据库前言简介SQLite连接SQLite创建数据表增删改查MySQLmysql-connector操作MySQL创建数据表增删改查pymysql操作MySQLMongoDB连接MongoDB增删改查Redis连接Redis前言本文是个人使用Python操作常用数据库的学习笔记,由于水平有限,难免出现错漏,敬请批评改正。简介数据......
  • 你真的了解Python吗?Python一些常见问题总结(一)
    你真的了解Python吗?Python一些常见问题总结(一)前言Python40问参考链接前言本文整理和解答了关于python的一些常见问题,由于水平有限,难免出现错漏,敬请批评改正。Python40问什么是Python?Python-百度百科Python官网Python3菜鸟教程Python是一种解释型语言。这就是说,与C语言和C的......
  • 为什么只有Python可以爬虫,C++可以吗?
    Python(英国发音:/ˈpaɪθən/;美国发音:/ˈpaɪθɑːn/),是一种广泛使用的解释型、面向对象、动态数据类型的高级程序设计语言。Python支持多种编程范型,包括结构化、过程式、反射式、面向对象和函数式编程。它拥有动态类型系统和垃圾回收功能,能够自动管理内存使用,并且其本身拥有一个......
  • Python虚拟环境,多版本共存-windows安装【记录】
    使用virtualenv可以快速创建干净的环境,并且可以指定版本。安装virtualenvpipinstallvirtualenv创建虚拟环境virtualenv-pD:\Python\Python36\python.exevenv36D:\Python\Python36\python.exe可以选择已安装的python版本venv36创建的虚拟环境的目录进入虚拟环境......