簡體   English   中英

如何從一個函數並行啟動2個(或更多)進程

[英]How to start 2 (or more) processes in parallel from a function

我試圖從一個類中的一個函數並行啟動2個進程,但無法正常工作。 我正在嘗試這樣的事情:

 from multiprocessing import Process

 class MyClass():

     #something here to create a large list L

     def myClassFunction1():
        #something here
        ....
        ....
     def myClassFunction2():
        #something here
        p1 = Process(target=myProcess1,args=(L,))
        p2 = Process(target=myProcess2,args=(L,))
        p1.start()
        p2.start()
        p1.join()
        p2.join()
        #something else here

    def myProcess1(L):
        #do something here with L

    def myProcess2(L):
        #do something here with L

我在python中不是很好.....而且我不太了解多處理的工作原理。 我希望有人能給我一些幫助。

謝謝!

您需要將這些函數稱為實例方法:

p1 = Process(target=self.myProcess1,args=(L,))
p2 = Process(target=self.myProcess2,args=(L,))

在您的輔助函數中,將self作為第一個參數:

def myProcess1(self, L):
    #do something awesome with L
def myProcess1(self, L):
    #do something as awesome as myProcess1 with L

希望這可以幫助!

我以前從未使用過多處理模塊,但是您可以使用線程模塊...

import threading

class worker (threading.Thread):
    def __init__(self,extraArgs):
        threading.Thread.__init__(self)
        self.storeArgs = extraArgs
    def run(self):
        //add code can use self.storeArgs


a = worker(argsA)
b = worker(argsB)
a.start()  //starts concurrent thread using worker.run()
b.start()  //starts concurrent thread using worker.run()

while threading.activeCount()>1:  //loop to make sure threads are finished running
    continue    

您可以為要運行的不同方法創建兩個類,也可以為工作人員提供兩個方法,並使用if / else或case邏輯來確定要在其run / start方法中使用哪個方法

在創建過程之前,只需定義功能即可。 Python解釋器逐行讀取模塊,直到到達創建進程的行時,才定義函數。

我建議您將這些功能放在單獨的模塊中,然后從那里導入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM