已经尝试通过现有的帖子来解决我的问题-但是,没有成功。提前感谢您的帮助。
目标是在线程之间共享一个变量。请找到下面的代码。它一直为会计变量打印'1',尽管我希望它打印'2'。为什么?有什么建议main.py:
account = 1
import threading
import cfg
import time
if __name__ == "__main__":
thread_cfg = threading.Thread(target=cfg.global_cfg(),args= ())
thread_cfg.start()
time.sleep(5)
print(account)
cfg.py:
def global_cfg():
global account
account = 2
return()
全局变量不能跨文件共享。
如果我们忽略锁和其他同步原语,只需将account
放在cfg.py
中:
account = 1
def global_cfg():
global account
account = 2
return
和main.py
内部:
import threading
import time
import cfg
if __name__ == "__main__":
thread_cfg = threading.Thread(target=cfg.global_cfg,args= ())
print(cfg.account)
thread_cfg.start()
time.sleep(5)
print(cfg.account)
运行:
> py main.py
1
2
在更高级的情况下,您应该使用Lock
s,Queue
s和其他结构,但这超出了范围。