gpt4 book ai didi

Python:从另一个线程更改变量值

转载 作者:行者123 更新时间:2023-12-03 13:09:24 25 4
gpt4 key购买 nike

为什么 my_string 的值没有改变?

我正在从两个不同的模块运行两个线程,模块 2 访问模块 1 的“set_string”以更改“my_string”的值,但是当模块 1 打印字符串时,它是空的。

第一个模块:

from threading import Thread
import Module2 as M2
import time

my_string = ""


def set_string(string):
global my_string
my_string = string


def mainloop1():
global my_string
while True:
print("Module 1: ", my_string)
time.sleep(1)

if __name__ == '__main__':
thread = Thread(target=M2.mainloop2)
thread.start()
mainloop1()

第二个模块:
import Module1 as M1
import time
import random


def mainloop2():
while True:
string = str(random.randint(0, 100))
print("Module 2: ", string)
M1.set_string(string)
time.sleep(1)

最佳答案

这是因为方法在不同的模块中实现,there are no truly global variables in python ; Module2 中引用的 set_string 正在更新其 globals()['M1'] 名称中的 my_string 变量,其中 Module1 正在更新直接存储在 globals()['my_string'] 中的 my_string 变量。

请注意,如果您将 mainloop2 的定义移动到 Module1 中,更新导入和 Thread 调用,那么您将获得预期的行为、不确定的执行顺序等等。

关于Python:从另一个线程更改变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40225016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com