简体   繁体   English

全局变量通过多线程 python

[英]Global variables through multithreading python

I have a file which I am monitoring, since I need two fields from it, the thing is that I have run into the problem that with the multithreading library I cannot share global variables, that is, I modify them in the main and in the processes they do not come out those modifications, I've been investigating and I can't find a solution.我有一个正在监视的文件,因为我需要其中的两个字段,问题是我遇到了使用多线程库我无法共享全局变量的问题,也就是说,我在主文件和主文件中修改它们过程他们没有出来那些修改,我一直在调查,我找不到解决方案。 The child processes that you have running must see in real time that modification that was made in the main您正在运行的子进程必须实时看到在主进程中所做的修改

WH = ''
delay = 0.0


def comprobar():
    print(WH)
    print(delay)


if __name__ == "__main__":

    while True: 

        with open("configUsers.json") as archivo:
            data = json.load(archivo)
            WH = data['WH']
            delay = data['delay']
            thread = multiprocessing.Process(name="hilo1", target=comprobar, args=())
            thread.start()
            time.sleep(0.5)

What OS are you running on?你在什么操作系统上运行? MacOS/Windows or Linux. MacOS/Windows 或 Linux。 I'm guessing the former.我猜是前者。

Python has two different ways of starting a subprocess. Python 有两种不同的启动子进程的方式。

In one case ("forking") it makes an exact copy of the world, and then calls the function.在一种情况下(“分叉”),它会精确复制世界,然后调用 function。 Forking is the default on Linux.分叉是 Linux 上的默认设置。 In this world, you'd see WH and delay with their updated values.在这个世界上,您会看到 WH 和延迟更新值。

In the other case ("spawning"), it starts a fresh Python image and reloads the file, but doesn't execute the code inside if __name__ == "__main__" .在另一种情况下(“生成”),它会启动一个新的 Python 图像并重新加载文件,但if __name__ == "__main__"则不执行其中的代码。 This is the default on Windows and MacOs.这是 Windows 和 MacO 上的默认设置。 In this case, your code would still see the values as "" and 0.0 .在这种情况下,您的代码仍会将值视为""0.0

In your case, you should just be passing WH and delay as arguments to comprobar() .在您的情况下,您应该将WHdelay作为 arguments 传递给comprobar() I expect you're actually trying to do something more complicated, but it's hard to tell from this limited example.我希望您实际上是在尝试做一些更复杂的事情,但是从这个有限的示例中很难看出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM