所以 - ypu 可能在某处读到“使用全局变量不是一个好习惯” - 这就是原因。您的“p”变量仅包含一个“进程”实例,并且它只能启动(和终止)一次。
如果你重构你的代码,让“fun1”和“fun2”把它们作为参数的进程,或者可能以OO方式,其中fun1和fun2是方法,进程是一个实例变量,你不会有任何这些问题。
在这种情况下,OO 可以快速查看并直接使用:
class MyClass(object):
def __init__(self):
self.p = Process(target=realwork,args=(up,down,middle,num))
def fun1(self):
self.p.start()
def fun2(self):
self.p.terminate()
然后,无论您需要对“fun1”和“fun2”进行一对调用,您都可以:
action = Myclass()
action.fun1()
action.fun2()
反而。这甚至可以在 for 循环或其他任何循环中工作。
*edit - I just saw ou are using this as answer to a button press in a Tkinter
program, so, you have to record the Process instance somewhere between button clicks.
Without having your code to refactor, and supposing you intend to persist
on your global variable approach, you can simply create the Process instance inside
"fun1" - this would work:
def fun1():
global p
p = Process(target=realwork,args=(up,down,middle,num))
p.start()
def fun2():
p.terminate()