0

code:

from threading import Timer, Event
from time import sleep

def hello(e):
    print e
    print 'Inside......'
    while True:
        if e.isSet():
            print "hello_world"
            break

if __name__ == '__main__':
    e = Event()
    t = Timer(1, hello(e,))
    t.start()
    print e.isSet()
    sleep(2)
    e.set()
    print e.isSet()

Output:

 [root@localhost ~]# python test_event.py 
<threading._Event object at 0x7f440cbbc310>
Inside......

In the above code, I am trying to understand the Timer and, Event objects from python. If I run the above code, the Timer invokes the function hello() and it runs indefinitely. The main thread is not executing the line next to t.start(). What am I missing here??

Thanks.

1
  • Possible duplicate of threading.Timer() Commented Jan 29, 2018 at 6:49

1 Answer 1

2

In your code,

t = Timer(1, hello(e,))

Instead of passing arguments to the thread, you are calling the function before creating the thread. hello(e,) calls the function which waits for the event e to set. Since it's stuck in an infinite loop here and doesn't return from the function hello, the thread creation is not happening and e is never set.

Just change it to a valid thread creation:

t = Timer(1, hello, [e])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for explaining it with clarity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.