Python多进程与多线程并发执行封装实战

林舟
林舟
发布时间:2026-10-13| 4人浏览过
原创

本文介绍Python中多进程与多线程的并发处理封装方法。通过自定义继承Process类的MyProcess,利用Queue实现结果收集,实现多进程并行执行函数。同时详解多线程创建、参数传递及setDaemon守护线程机制,解决父进程退出导致子线程中断的问题,适用于自动化测试及高并发场景。

Python多进程并发处理封装

本文直接展示核心代码实现,省略冗余说明。

多进程核心代码实现


import multiprocessing as mp
from multiprocessing import Process
class MyProcess(Process):
  """
  自定义多进程,继承自原生Process,目的是获取多进程结果到queue
  """
  def __init__(self, func, args, q):
    super(MyProcess, self).__init__()
    self.func = func
    self.args = args
    self.res = ''
    self.q = q
    #self._daemonic = True
    #self._daemonic = True
 
  def run(self):
    self.res = self.func(*self.args)
    self.q.put((self.func.__name__, self.res))
  
def use_multiprocessing(func_list):
  #os.system('export PYTHONOPTIMIZE=1') # 解决 daemonic processes are not allowed to have children 问题
  q = mp.Queue() # 队列,将多进程结果存入这里,进程间共享, 多进程必须使用 multiprocessing 的queue
  proc_list = []
  res = []
  for func in func_list:
    proc = MyProcess(func['func'], args=func['args'], q=q)
    proc.start()
    proc_list.append(proc)
 
  for p in proc_list:
    p.join()
  while not q.empty():
    r = q.get()
    res.append(r)
  return res

调用时,将待多进程执行的函数及其参数封装为字典列表,传入use_multiprocessing方法即可运行。

多线程并发执行详解

补充知识:在Python单个文件中实现多个函数的并发执行(多进程方式)。

具体实现代码如下。

多线程基础代码示例


 #coding=utf-8
import time
from selenium import webdriver
import threading

def fun1(a):
  print a

def fun2():
  print 222

threads = []
threads.append(threading.Thread(target=fun1,args=(u'爱情买卖',)))
threads.append(threading.Thread(target=fun2))
print(threads)
if __name__ == '__main__':
  for t in threads:
    t.setDaemon(True) #我拿来做selenium自动化模拟多个用户使用浏览器的时候,加了这个就启动不了,要去掉
    t.start()

import threading

首先导入threading模块,这是使用多线程的基础前提。


threads = []
t1 = threading.Thread(target=fun1,args=(u'爱情买卖',))
threads.append(t1)

创建threads列表,初始化线程t1。使用threading.Thread()方法,通过target参数指定目标函数music,并通过args参数传递参数。将创建好的线程t1添加至threads数组中。

以相同方式创建线程t2,并将其加入threads数组。


for t in threads:
  t.setDaemon(True)
  t.start()

最后通过for循环遍历该数组(数组中已包含t1和t2两个线程对象)。

setDaemon()

守护线程机制与注意事项

调用setDaemon(True)将线程声明为守护线程,此设置必须在start()方法调用前完成。若不设为守护线程,程序可能被无限挂起。子线程启动后,父线程继续执行,当父线程执行完最后一条语句print "all over %s" %ctime()后,若未等待子线程直接退出,子线程也将随之结束。

start()

调用start()方法启动线程活动。

后记:

自动化测试中的并发应用

尝试进行并发浏览器操作,

若需进行参数化测试,使用ddt框架会导致所有行为在单一浏览器实例中执行;移除ddt框架后,并发功能恢复正常。

以上关于Python多进程函数封装的实例即为全部内容,希望能对读者有所帮助,欢迎支持本站。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。