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

StackOverflow https://stackoverflow.com/questions/21973088

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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top