Reputation: 8201
How to determine if a python thread has been started? There is a method is_alive()
but this is true before and while a thread is running.
Upvotes: 6
Views: 7131
Reputation: 22561
Use isAlive
(or is_alive
) Thread
class method.
Python 2.7 http://hg.python.org/cpython/file/2.7/Lib/threading.py#l995
def isAlive(self):
"""Return whether the thread is alive.
This method returns True just before the run() method starts until just
after the run() method terminates. The module function enumerate()
returns a list of all alive threads.
"""
assert self.__initialized, "Thread.__init__() not called"
return self.__started.is_set() and not self.__stopped
Python 3 https://github.com/python/cpython/blob/master/Lib/threading.py
def is_alive(self):
"""Return whether the thread is alive.
This method returns True just before the run() method starts until just
after the run() method terminates. The module function enumerate()
returns a list of all alive threads.
"""
assert self._initialized, "Thread.__init__() not called"
if self._is_stopped or not self._started.is_set():
return False
self._wait_for_tstate_lock(False)
return not self._is_stopped
Upvotes: 2
Reputation: 711
You can look at the ident field of the Thread instance. The Python 2.7 documentation for Threading describes ident as
The ‘thread identifier’ of this thread or None if the thread has not been started.
Upvotes: 9
Reputation: 500167
You could have the thread function set a boolean flag on startup, and then check that flag.
Upvotes: 1