Python threading timer initial daemon
Asked Answered
S

1

12

This code is not working......

self._thread = threading.Timer(interval=2, 
                               function=self._sendRequestState, 
                               args=(self._lockState,), 
                               daemon=True).start()

So I should write down like this..

self._thread = threading.Timer(interval=2, 
                               function=self._sendRequestState, 
                               args=(self._lockState,))
self._thread.daemon = True
self._thread.start()

But the Timer class has Thread.__init__, Thread.__init__ has "daemon" for input parameter. I don't have any idea why it doesn't work...

Sudor answered 2/3, 2018 at 17:53 Comment(2)
Are there any other statements in your code? Why are you making the thread a daemon thread? If you have no other statements, python will exit if only daemon threads are left, and your thread will never have time to execute.Steeplebush
@BrendanAbel There are many threads :) Thank u!Sudor
P
13

You can find the source code of that threading.Thread() constructor here (of cpython, the most common python implementation):

def __init__(self, interval, function, args=None, kwargs=None):
    Thread.__init__(self)
    self.interval = interval
    self.function = function
    self.args = args if args is not None else []
    self.kwargs = kwargs if kwargs is not None else {}
    self.finished = Event()

If you pass daemon=True into it, that will be put in kwargs, but as you can see in the code, nothing happens with it. So yes, you're correct, you'll have to set the daemon attribute after creating it (and before calling start(). There seems to be no option to set it directly when constructing the Timer.

Pubes answered 2/3, 2018 at 18:16 Comment(1)
No, the daemon argument will not be put in kwargs, because kwargs here is a single keyword argument, and not a double-star catcher. What happens when passing daemon=True is a TypeError.Geranial

© 2022 - 2024 — McMap. All rights reserved.