简体   繁体   English

Python 中的 threading.Timer — 两个函数同意变量标识,但不同意值

[英]threading.Timer in Python — two functions agree on variable identity, but not the value

Are there any caveats similar to variable caching when using threading.Timer in Python?在 Python 中使用 threading.Timer 时是否有任何类似于变量缓存的警告?

I'm observing an effect similar to not putting " volatile " keyword in other languages, but I've read that this doesn't apply to Python and yet something is off.我观察到类似于不在其他语言中放置“ volatile ”关键字的效果,但我已经读到这不适用于 Python 并且有些东西是关闭的。 In summary, two methods (threads?) agree on the identity of a list variable but disagree on the contents.总之,两种方法(线程?)在列表变量的身份上达成一致,但在内容上存在分歧。

I have a class with member variable self.x (a list) which is assigned once in constructor and then its identity never changes (but it can be cleared and refilled).我有一个 class 和成员变量 self.x (一个列表),它在构造函数中分配一次,然后它的标识永远不会改变(但它可以被清除和重新填充)。

A Timer is also started in the constructor that periodically updates the contents of self.x. Timer 也在构造函数中启动,它定期更新 self.x 的内容。 I'm not using any locks though I probably should (eventually).尽管我可能应该(最终)使用任何锁,但我没有使用任何锁。

Other users of the class instance then sometimes try to read the contents of the list. class 实例的其他用户有时会尝试读取列表的内容。

Problem: At the end of the timer handler, the list is populated correctly (I've printed its contents in the logs) but when a user of the class instance reads the instance variable, it's empty, (more specifically, same value as it was initialized in the constructor. ie, if I put some other item in there. it'll be that value).问题:在计时器处理程序结束时,列表被正确填充(我已经在日志中打印了它的内容)但是当 class 实例的用户读取实例变量时,它是空的,(更具体地说,与它相同的值在构造函数中初始化。即,如果我在那里放了一些其他项目。它将是那个值)。

The weird thing is that the getter and the timer agree on the identity of the list!奇怪的是,getter 和 timer 在列表的身份上是一致的! ( id(self.x) returns the same value ). id(self.x) 返回相同的值)。 Also, I was not able to repro this in tests, even though I'm doing the same thing.此外,即使我在做同样的事情,我也无法在测试中重现这一点。

Any idea what I might be doing wrong?知道我可能做错了什么吗?

Thanks in advance!提前致谢!

Seems like I misunderstood how multiprocessing works.好像我误解了多处理的工作原理。 What happened is the code forked into multiple processes and even though the id() of objects remained the same, I didn't realize they were in different (forked) processes.发生的事情是将代码分叉到多个进程中,即使对象的 id() 保持不变,我也没有意识到它们处于不同的(分叉)进程中。 I knew this was happening but I thought that the fork would take care of copying the timer as well.我知道这正在发生,但我认为 fork 也会负责复制计时器。 I've changed the code to create the object (and timers) once the fork is complete and it seems to have solved the problem.一旦分叉完成,我已经更改了代码以创建 object(和计时器),并且似乎已经解决了问题。

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

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