如何在其他进程完成时终止进程?

How to terminate a process when other process finishes?

我创建了三个函数,第一个函数我创建了一个倒数计时器,另外两个函数我找到素数。我正在使用 multiprocessing 让它们一起执行。我想让它做的是当计时器完成时,其他两个进程也将终止。其他两个函数将继续搜索素数,直到计时器结束,例如如果定时器设置为 1 分钟,函数将继续搜索素数一分钟。

现在代码在检查下一个数字之前等待 n 秒。我所做的是,当它们达到 0 时,我将倒计时函数传递给其他两个函数以终止其他两个函数内的循环。

这是我的代码:

import time
import sys
from multiprocessing import Process

def countdown(t): 
    while t:
        mins, secs = divmod(t, 60) 
        timer = '{:02d}:{:02d}'.format(mins, secs) 
        print(timer, end="\r") 
        time.sleep(1) 
        t -= 1

def isPrime1():
    f = open('results.txt','w')
    i = 2
    while countdown(t) != 0:
        c = 0;
        for j in range (1, (i + 1), 1):
            a = i % j
            if (a == 0):
                c = c + 1

        if c == 2:
            f.write(str(i))
            print(i)
            if countdown(t) == 0:
                break
        i = i + 1
    f.close()

def isPrime2():
    f = open('results1.txt','w')
    i = 2
    while countdown(t) != 0:
        mins, secs = divmod(t, 60)
        c = 0;
        for j in range (1, (i + 1), 1):
            a = i % j
            if (a == 0):
                c = c + 1

        if c == 2:
            f.write(str(i))
            print(i)
            if countdown(t) == 0:
                break
        i = i + 1
    f.close()

if __name__=='__main__':
    t = int(input("Seconds:"))
    p1 = Process(target=isPrime1())
    p1.start()
    p2 = Process(target=isPrime2())
    p2.start()
    p3 = Process(target=countdown(t))
    p3.start()

请查看 Conditions, Events 和其他同步原语。

PS:它在任何方面都比任何一种全局变量都要好(因为进程不共享它们的状态,并且每个进程在fork期间都会有自己的从父进程继承的状态副本).

您想使用 Events。它们是一种用于进程间通信的同步技术,建立在 lock/mutex.

等同步原语之上

每个进程都有自己分配的内存区域,其中分配了变量,因此变量不会在不同进程之间共享。这是进程和线程之间的主要区别之一(线程共享相同的内存)。 当您创建(=fork)一个进程时,原始(父)进程的变量被复制到新进程(子)内存区域中。所以他们一开始会有相同的值,但是fork之后所做的更改不会被其他进程看到。

在您的情况下,每个进程都有自己的 t 变量副本,并且看不到其他进程对其副本所做的更改。

将此视为示例程序,它使用事件执行您想要的操作:

import time
from multiprocessing import Process, Event

def countdown(event, t):
    while t:
        mins, secs = divmod(t, 60)
        timer = '{:02d}:{:02d}'.format(mins, secs)
        print(timer, end="\r")
        time.sleep(1)
        t -= 1
    # Set the event to notify the other processes
    event.set()
    print("Countdown done")

def isPrime(event):
    # This loop ends when the countdown is over
    while not event.is_set():
        # Your code here
        pass
    print("Done!")

if __name__=='__main__':

    t = int(input("Seconds:"))
    event = Event() # the event is unset when created
    p1 = Process(target=isPrime, args=(event,))
    p1.start()
    p2 = Process(target=isPrime, args=(event,))
    p2.start()
    p3 = Process(target=countdown, args=(event,t,))
    p3.start()
    p1.join()
    p2.join()
    p3.join()

这是结果:

P.S。您不需要复制该函数的代码。您可以使用相同的函数 运行 任意数量的进程。他们将独立进行。 您还应该使用 join 让原始进程等待其子进程结束。