Python哪个线程首先启动?
关于python 2.7Python哪个线程首先启动?,python,multithreading,Python,Multithreading,关于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="MyTh
#!/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()
美元/螺纹,如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)>]
i是:0
[, ]
我是:1
[, ]
我是:2
[, ]
我是:3
[, ]
我是:4
[, ]
问题:
为什么开始时间指示主线程在MyThread1之后开始?即
MainThread\u starttime-MyThread1\u starttime>0输出没有说明哪个线程首先启动,也不清楚您为什么认为它会启动。你在看140502713374464这样的整数吗?如果是,则这些值是由
Thread.ident()
返回的,与时间戳无关。只需查看线程的代码即可
def\uuu repr\uu(自):
assert self.\u initialized,“未调用线程.\uuuuu init\uuuuuu()”
status=“初始”
如果self.\u已启动。是否设置()
status=“已开始”
self.is_alive()#容易获取。_在适当时设置为停止
如果self.\u已停止:
status=“已停止”
如果self.\u daemonic:
状态+=“守护进程”
如果self.\u ident不是无:
状态+=%s”%self.\u ident
返回“”%(self.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
整数取自self.\u ident
,它是平台分配给线程的任何唯一整数标识符的缓存值
在更高的级别上,当线程启动时,CPython不会存储任何记录,因此,不仅示例输出不会显示该信息,其他信息也不会显示。如果你想跟踪它,你需要自己实现它(比如说,在线程
子类捕获开始时间)。快速无效的回答,因为我在手机上,但是阅读线程模块的源代码,它应该变得清晰:-)这就是我在评论中的意思:)
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)