下面是我创建的示例。本质上,我将两个过程定义为全局变量(是的,我知道这是不好的做法,但我这样做是为了说明问题)。killer
进程的目标是kill_printer
函数,它在5秒后终止printer
进程。这两个进程都是global
对象,所以这应该不是问题。你知道吗
from time import sleep
from multiprocessing import Process
def kill_printer():
print('printer' in globals() and 'killer' in globals())
sleep(5)
printer.terminate()
def print_hello():
while True:
print('hello')
sleep(1)
if __name__ == '__main__':
global printer
global killer
printer = Process(target=print_hello)
killer = Process(target=kill_printer)
printer.start()
killer.start()
print('printer' in globals() and 'killer' in globals())
但是,正如您所看到的,我已经打印了一些测试来确认printer
和killer
都是全局变量,在它们的定义之后,以及在kill_printer
中需要printer
。这是因为程序运行时,结果如下:
True
hello
False
hello
hello
hello
hello
hello
Process Process-2:
Traceback (most recent call last):
File "C:\Users\Alex\AppData\Local\Programs\Python\Python35\lib\multiprocessing\process.py", line 254, in _bootstrap
self.run()
File "C:\Users\Alex\AppData\Local\Programs\Python\Python35\lib\multiprocessing\process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Alex\Google Drive\EES\test.py", line 7, in kill_printer
printer.terminate()
NameError: name 'printer' is not defined
hello
hello
hello
hello
一分钟后,两个进程都在globals
中,但突然之间它们不在了(导致NameError
,并且printer
正在打印!这里发生了什么?这个问题是否与我通常使用的过程或变量本身有关?你知道吗
(如果有人要回答multiprocessing
在这里是不必要的,他们应该知道给定的示例是一个简化的程序示例,这个程序肯定是这样做的)
目前没有回答
相关问题 更多 >
编程相关推荐