问题:进程1结束后如何停止进程2?
更长的版本:我编写了一个脚本,该脚本可以多进程处理2个函数,我真的不知道在第一个进程完成后如何停止第二个进程。
我的代码:
def printHelloWorld(): # So this takes 5.0053 seconds to completly run
print("Hello World.")
time.sleep(5)
print("Hello World. (after 5 seconds)")
def printText(): # And this takes 10.0102 seconds to completly run
print("Some text.")
time.sleep(10)
print("Some text. (after 10 seconds)")
if __name__ == "__main__": # I multiprocessed these 2 functions to reduce time.
# But what I actually want is to terminate process 2 when process 1 has finished.
p1 = Process(target = printHelloWorld)
p2 = Process(target = printText)
p1.start()
p2.start()
p1.join()
p2.join()
我尝试了一个while循环来检查p1.is_alive == False
的时间,然后我应该终止进程2,但这没有用。我也搜索了答案,但没有找到符合我要求的答案。
感谢您阅读/回答!
让我澄清一些事情:很抱歉,如果我不能正确解释它,但是我想问的是,由于不再需要哪个,我该如何检查哪个先完成并终止第二个过程? / p>
示例:如果我们不知道函数1和2的执行时间(两个函数处于并行进程中)怎么办?因此,一旦第一个进程停止,我希望另一个进程也停止。我怎样才能做到这一点?我希望现在对此进行清楚的描述。再次抱歉造成混乱!
答案 0 :(得分:1)
您尝试过Process.terminate
吗?
import time
from multiprocessing import Process
def printHelloWorld(): # So this takes 5.0053 seconds to completly run
print("Hello World.")
time.sleep(5)
print("Hello World. (after 5 seconds)")
def printText(): # And this takes 10.0102 seconds to completly run
print("Some text.")
time.sleep(10)
print("Some text. (after 10 seconds)")
if __name__ == "__main__": # I multiprocessed these 2 functions to reduce time.
# But what I actually want is to terminate process 2 when process 1 has finished.
p1 = Process(target = printHelloWorld)
p2 = Process(target = printText)
p1.start()
p2.start()
p1.join()
p2.terminate() # terminate process 2
p2.join()
答案 1 :(得分:1)
我建议您使用Pebble库。它包装了Python的标准库线程和多处理对象。但是它有取消正在运行的呼叫的可能性很大。
import time
from concurrent.futures import wait, FIRST_COMPLETED
from pebble import ProcessPool
def printHelloWorld(): # So this takes 5.0053 seconds to completly run
print("Hello World.")
time.sleep(5)
print("Hello World. (after 5 seconds)")
def printText(): # And this takes 10.0102 seconds to completly run
print("Some text.")
time.sleep(10)
print("Some text. (after 10 seconds)")
if __name__ == "__main__": # I multiprocessed these 2 functions to reduce time.
with ProcessPool(max_workers=2) as pool:
f1 = pool.schedule(printHelloWorld)
f2 = pool.schedule(printText)
done, not_done = wait((f1, f2), return_when=FIRST_COMPLETED)
for f in not_done:
f.cancel()