为什么即使我使用threading.lock(),输出也如此混乱?

发布于 2025-01-31 19:10:46 字数 1488 浏览 1 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

惟欲睡 2025-02-07 19:10:46

这是由行self.count += a引起的。您不是将值增加1,而是通过当前索引。因此,第一个迭代是count + 1,计数等于1,然后count + 2,计数等于2(因为您在上一个迭代中更改了)。 。

第二件事是您的count变量不是静态的,这意味着对象的每个实例都会获得其自身变量,即当前对象的本地变量,这就是为什么第二个对象再次开始为1。如果您希望它在所有情况下都是全局

This is caused by the line self.count += a. You're not incrementing the value by 1, but by the current index. So the first iteration is count + 1 with count equals to 1, then count + 2 with count equals to 2 (because you changed it in the previous iteration), ... Simply use a self.count += 1.

The second thing is that your count variable is not static, that means that each instance of the object gets its own variables, local to the current object, that's why the second object starts at 1 again. If you want it to be global to all instances, just declare it outside any method (like you did for the lock)

国粹 2025-02-07 19:10:46

锁工作正常,问题在循环中。尝试一个无线程的简单代码,

count = 1
for a in range(10):
    x += a
    print(count)

这将打印相同的输出,因为您在每次迭代中都会增加count a

1
2
4
7
11
16
22
29
37
46

以将输出作为1,2,3, 4 ...您可以做这样的事情

count = 0
for a in range(10):
    count += 1
    print(count)

The lock is working fine, the issue is in the loop. Try a simple code without threads

count = 1
for a in range(10):
    x += a
    print(count)

this will print the same output, since you increase count by a in every iteration

1
2
4
7
11
16
22
29
37
46

To get the output as 1, 2, 3, 4... you can do something like this for example

count = 0
for a in range(10):
    count += 1
    print(count)
回忆追雨的时光 2025-02-07 19:10:46

我不确定我是否正确理解了您的问题

self.count += a  
# should be self.count += 1

I am not sure if I understand your question correctly but it seems that you add a to count instead of 1 each time

self.count += a  
# should be self.count += 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文