我正在编写一个程序来创建两个新进程,并且必须等待它们完成才能继续。如何启动这两个进程并让程序等待两个进程退出?考虑伪代码:
我目前有:
create_process("program1.exe").wait()
create_process("program2.exe").wait()
这很棒,因为program2可以与program1一起运行。
create_process("program1.exe")
create_process("program2.exe").wait()
这可能是错误的,因为program1可能需要比program2更长的时间。
我对一般解决方案感兴趣,我敢打赌,为了解决这个问题,我发明了算法或设计模式。但是要为问题添加上下文,我正在编写一个调用pgsql2shp.exe两次的Python脚本,将两个表从数据库导出到本地计算机,然后预先形成一个交集。此脚本使用Python 2.7编写,并使用subprocess.popen
答案 0 :(得分: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