Ankur Agarwal
Ankur Agarwal

Reputation: 24748

Python which thread starts first?

On python 2.7

#!/usr/bin/env python
import time, threading, os
def f1(arg1):
    for i in xrange(arg1):
        time.sleep(1)
        print "i is: ", i
        print threading.enumerate()

if __name__ == '__main__':
    t = threading.Thread(name="MyThread1", target=f1, args=(5,))
    t.start()
    t.join()

$ ./threadeg.py

i is:  0
[<_MainThread(MainThread, started 140502713374464)>, <Thread(MyThread1, started 140502683985664)>]

i is:  1
[<_MainThread(MainThread, started 140502713374464)>, <Thread(MyThread1, started 140502683985664)>]

i is:  2
[<_MainThread(MainThread, started 140502713374464)>, <Thread(MyThread1, started 140502683985664)>]

i is:  3
[<_MainThread(MainThread, started 140502713374464)>, <Thread(MyThread1, started 140502683985664)>]

i is:  4
[<_MainThread(MainThread, started 140502713374464)>, <Thread(MyThread1, started 140502683985664)>]

Question:

Why do the started times indicate that main thread started after MyThread1? i.e. MainThread_starttime - MyThread1_starttime > 0

Upvotes: 1

Views: 152

Answers (1)

Tim Peters
Tim Peters

Reputation: 70582

The output says nothing about which thread was started first, and it's unclear why you think it does. Are you looking at the integers like 140502713374464? If so, those are the values returned by Thread.ident(), and have nothing to do with timestamps. Just look at the code for Thread.__repr__():

def __repr__(self):
    assert self._initialized, "Thread.__init__() was not called"
    status = "initial"
    if self._started.is_set():
        status = "started"
    self.is_alive() # easy way to get ._is_stopped set when appropriate
    if self._is_stopped:
        status = "stopped"
    if self._daemonic:
        status += " daemon"
    if self._ident is not None:
        status += " %s" % self._ident
    return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status)

The integers are taken from self._ident, which is a cached value of whatever unique integer identifier the platform assigns to the thread.

At a higher level, CPython stores nothing recording when a thread was started, so not only does your sample output not reveal that information, nothing else would either. If you want to keep track of that, you would need to implement it yourself (in, say, a Thread subclass capturing start time).

Upvotes: 3

Related Questions