简体   繁体   中英

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? ie MainThread_starttime - MyThread1_starttime > 0

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM