我在下面编写的程序中发现,在我调用start()
之后,loop_a()
进程没有立即打印。只有输入一些文本,loop_a()
进程才能启动()。
如果在调用start()
之后调用run(),则loop_a()
进程将立即运行。但是从不碰到main()
while循环。
谁能解释我为什么会这样?
from multiprocessing import Process, Manager
import time
def loop_a(go):
while True:
# run forever and print out the msg if the flag is set
time.sleep(1)
print("a")
if __name__ == '__main__':
# shared value flag
manager = Manager()
go_flag = manager.Value('flag', True)
# other process that is printing
Process(target=loop_a, args=(go_flag,)).start()
#Process(target=loop_a, args=(go_flag,)).run()
# normal main thread; toggle on and off the other process
while True:
text = input('Stop Y/N?')
if text == 'Y':
go_flag.value = False
print("Changed the flag {}".format(go_flag.value))
else:
go_flag.value = True
print("Changed the flag {}".format(go_flag.value))