在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)>]
问题:
为什么开始时间表明主线程在 MyThread1之后开始?即 MainThread_starttime - MyThread1_starttime&gt; 0
答案 0 :(得分:3)
输出没有说明首先启动了哪个线程,并且不清楚为什么你认为它会这样做。你在看140502713374464这样的整数吗?如果是这样,那些是Thread.ident()
返回的值,与时间戳无关。只需查看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)
整数取自self._ident
,它是平台为线程分配的任何唯一整数标识符的缓存值。
在更高级别,CPython在线程启动时不存储任何记录,因此您的示例输出不仅不会显示该信息,也不会显示任何其他信息。如果你想跟踪它,你需要自己实现它(例如,一个Thread
子类捕获开始时间。)