0

我正在編寫一個程序,該程序創建兩個新進程,並且必須等待它們完成後才能繼續。如何啓動這兩個進程並讓程序等待兩者退出?考慮僞代碼:等待兩個子進程完成但不一定先等待

我目前有:

create_process("program1.exe").wait() 
create_process("program2.exe").wait() 

這enificent作爲程序2可與程序1 concurently運行。

create_process("program1.exe") 
create_process("program2.exe").wait() 

這可能是錯誤的,因爲program1可能需要比program2更長的時間。

我對一個通用解決方案感興趣,我敢打賭有算法或設計模式發明處理這個東西。但是爲了給這個問題添加上下文,我正在編寫一個Python腳本,它會調用pgsql2shp.exe兩次,將兩個表從數據庫導出到本地機器,然後執行一個交集。這個腳本是用Python 2.7編寫的並且使用subprocess.popen

+0

那麼你怎麼究竟想象這?你不能保證2個過程將花費相同的時間。如果你想等待兩者都完成,總是會有一種情況,當一個比另一個更早完成時。 – matino

+0

@matino是的,我想等待兩者,但我希望在等待它們之前啓動它們......所以我想我應該在兩個都啓動後調用wait()。謝謝 – Celeritas

回答

2

如何使用線程? 如果啓動一對線程,每個線程都可以獨立運行,並且可以在線程完成時加入。

嘗試一些像這樣的代碼:(此代碼是大量註釋,這樣你可以遵循這是怎麼回事)

# Import threading 
import threading 

# Create a handler class. 
# Each instance will run in it's own independent thread 
class ThreadedHandler (threading.Thread): 

    # This method is called when you call threadInstance.start() 
    def run(self): 

     # Run your sub process and wait for it 
     # How you run your process is up to you 
     create_process(self.programName).wait() 

# Create a new thread object 
thread1 = ThreadedHandler() 

# Set your program name so that when the thread is started 
# the correct process is run 
thread1.programName = 'program1.exe' 

# Start the thread 
thread1.start() 

# Again, create a new thread object for the 2nd program 
thread2 = ThreadedHandler() 

# Set the program name 
thread2.programName = 'program2.exe' 

# Start the thread 
thread2.start() 

# At this point, each program is running independently in separate threads 
# Each thread will wait for their respective sub process to complete 

# Here, we join both threads. (Wait for both threads to complete) 
thread1.join() 
thread2.join() 

# When we get here, both of our programs are finished and they both ran in parallel 
+0

甚至可以使用'multiprocessing'包,它具有幾乎與'threading'相同的API – matino