python多进程使用函数封装实例

Liana ·
更新时间:2024-09-21
· 815 次阅读

我就废话不多说了,直接看代码吧!

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

使用时候,将需要多进程执行的函数和函数的参数当作字段,组成个list 传给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()方法,在这个方法中调用music方法target=music,args方法对music进行传参。 把创建好的线程t1装到threads数组中。

接着以同样的方式创建线程t2,并把t2也装到threads数组。

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

最后通过for循环遍历数组。(数组被装载了t1和t2两个线程)

setDaemon()

setDaemon(True)将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。子线程启动后,父线程也继续执行下去,当父线程执行完最后一条语句print "all over %s" %ctime()后,没有等待子线程,直接就退出了,同时子线程也一同结束。

start()

开始线程活动。

后记:

搞了个并发浏览器操作,

如果要做参数化,用ddt会导致所有行为都在一个浏览器操作,去掉ddt框架后,并发正常

以上这篇python多进程使用函数封装实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持软件开发网。

您可能感兴趣的文章:Python中使用多进程来实现并行处理的方法小结Python实现多进程的四种方式Python并发之多进程的方法实例代码python使用多进程的实例详解



进程 封装 函数 函数封装 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号