简体   繁体   English

Python线程计时器问题

[英]Python threaded timer issue

In this piece of code, I expected to see a random element in the list go to 1 for a minimum of 5 seconds. 在这段代码中,我希望看到列表中的随机元素至少在5秒钟内变为1。 Frequently I am seeing an element go to 1 for only a couple of iterations, then be reset to 0. What am I missing? 我经常看到元素只经过几次迭代就变为1,然后重置为0。我缺少什么? Does it have to do with threads not shutting down? 它与线程不关闭有关吗? Can someone please tell me how to fix it? 有人可以告诉我如何解决吗?

import threading
import random
import time


def lreset(x):
    global flags
    flags[x] = 0
    return

flags = [0,0,0,0,0,0,0,0]

while True:
    index = random.randint(0,7)
    flags[index] = 1
    t = threading.Timer(5, lreset, [index])
    t.start()

    print flags
    time.sleep(1)

This happens because there might be multiple timers waiting to reset the same index. 发生这种情况是因为可能有多个计时器正在等待重置同一索引。 Imagine that on first and third rounds random.randint returns same index. 想象一下,在第一轮和第三轮中random.randint返回相同的索引。 In the output for first five rounds the index would be 1 . 在前五个回合的输出中,索引为1 Then on sixth round the output would be reset back to 0 just as you would expect. 然后,在第六轮,将按照您的期望将输出重置为0

Now if random.randint would return the the same index again on seventh round the output would show the index as 1 . 现在,如果random.randint将在第七轮再次返回相同的索引,则输出将显示索引为1 Then before the eight round the timer set on third round would reset the index thus it would show as 0 on eight round output. 然后,在第八轮之前,在第三轮设置的计时器将重置索引,因此在第八轮输出中它将显示为0

One way to get the expected behavior is to ensure that you don't set the index if it's already set: 获得预期行为的一种方法是,确保没有设置索引(如果已设置):

while True:
    index = random.randint(0,7)
    if flags[index] == 0:
        flags[index] = 1
        t = threading.Timer(5, lreset, [index])
        t.start()

    print flags
    time.sleep(1)

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

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