In the python documentation at http://docs.python.org/2/library/threading.html#thread-objects it says that
[isAlive()] returns True just before the run() method starts until just after the run() method terminates
But then the start() method says that:
[start()] arranges for the object’s run() method to be invoked in a separate thread of control.
Does this mean if I call t.start()
and then immediately check t.isAlive()
it's possible I could get False
because the thread hasn't started yet?
The isAlive function − It is used to check if a thread is alive or not. Alive refers to a thread that has begun but not been terminated yet. When the run method is called, the thread operates for a specific period of time after which it stops executing.
The isAlive() method of thread class tests if the thread is alive. A thread is considered alive when the start() method of thread class has been called and the thread is not yet dead. This method returns true if the thread is still running and not finished.
A Python thread is just a regular OS thread. If you don't join it, it still keeps running concurrently with the current thread. It will eventually die, when the target function completes or raises an exception.
This method is used to find out if a thread has actually been started and has yet not terminated. Note: While returning this function returns true if the thread upon which it is called is still running. It returns false otherwise.
It can't happen, at least not in CPython's implementation. That comes from staring at the code for Thread.start
(here from the Python 3 source, but it doesn't matter):
def start(self):
...
try:
_start_new_thread(self._bootstrap, ())
except Exception:
with _active_limbo_lock:
del _limbo[self]
raise
self._started.wait()
_start_new_thread()
is implemented in C, starting a new thread and running self._bootstrap()
inside that new thread. self._bootstrap()
in turn invokes self.run()
. If that's all there were to it, then the invoking thread could indeed return an arbitrary amount of time before run()
started to execute. But the:
self._started.wait()
at the end blocks on an internal Event
. The bootstrap code sets the _started
Event
shortly before invoking run()
, and the state of that same event is the primary thing isAlive()
looks at.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With