歡迎您光臨本站 註冊首頁

python多進程使用函數封裝實例

←手機掃碼閱讀     niceskyabc @ 2020-05-03 , reply:0

我就廢話不多說了,直接看代碼吧!
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()
開始線程活動。


[niceskyabc ] python多進程使用函數封裝實例已經有283次圍觀

http://coctec.com/docs/python/shhow-post-232595.html