简体   繁体   中英

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. Frequently I am seeing an element go to 1 for only a couple of iterations, then be reset to 0. What am I missing? 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. In the output for first five rounds the index would be 1 . Then on sixth round the output would be reset back to 0 just as you would expect.

Now if random.randint would return the the same index again on seventh round the output would show the index as 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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