The Python Oracle

Can isAlive() be False immediately after calling start() because the thread hasn't yet started?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001

--

Chapters
00:00 Can Isalive() Be False Immediately After Calling Start() Because The Thread Hasn'T Yet Started?
00:38 Accepted Answer Score 6
01:25 Thank you

--

Full question
https://stackoverflow.com/questions/2197...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #multithreading #racecondition

#avk47



ACCEPTED ANSWER

Score 6


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.