This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
这是由行
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 iscount + 1
with count equals to 1, thencount + 2
with count equals to 2 (because you changed it in the previous iteration), ... Simply use aself.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)锁工作正常,问题在循环中。尝试一个无线程的简单代码,
这将打印相同的输出,因为您在每次迭代中都会增加
count
a以将输出作为
1,2,3, 4 ...
您可以做这样的事情The lock is working fine, the issue is in the loop. Try a simple code without threads
this will print the same output, since you increase
count
bya
in every iterationTo get the output as
1, 2, 3, 4...
you can do something like this for example我不确定我是否正确理解了您的问题
I am not sure if I understand your question correctly but it seems that you add a to count instead of 1 each time