我尝试测试一些进程线程,该线程将以标志变量结束,但它无法感知标志的变化并继续无限循环。
from multiprocessing import Process, Queue
from time import sleep
flag = 1
def threadTest():
while 1:
if flag == 1:
print('hi')
else:
break
sleep(0.1)
def main():
global flag
thread = Process(target=threadTest)
thread.start()
sleep(5)
flag = 0
thread.join()
print('thread exit')
if __name__ == "__main__":
main()
我的全局变量声明有问题吗?
最佳答案
您实际上是在创建一个进程,而不是一个线程。 创建新进程时,main 的状态会“复制”到新进程,并且现在独立于主进程。因此,对于该新进程,标志始终为 1。
只需导入线程
并更改为:
thread = threading.Thread(target=threadTest)
它应该可以工作。
我还会建议将 flag
更改为 bool 值,因为它用作循环的条件。
关于python - 进程线程无法感知全局变量的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57106179/