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

2022-10-07,,,,

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

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多进程使用函数封装实例.doc》

下载本文的Word格式文档,以方便收藏与打印。