- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
Python 版本:'2.7.3(默认,2013 年 4 月 10 日,06:20:15)\n[GCC 4.6.3]'
我有这个:
#!/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.active_count()
print threading.enumerate()
if __name__ == '__main__':
t = threading.Thread(name="MyThread1", target=f1, args=(5,))
t.start()
我的问题是,为什么事件线程数报告为 2,为什么 enumerate
生成的列表也包含主线程。
我在想主线程在生成“MyThread1”后终止。
$./threadeg.py
i is: 0
2
[<_MainThread(MainThread, stopped 139858183157504)>, <Thread(MyThread1, started 139858153768704)>]
i is: 1
2
[<_MainThread(MainThread, stopped 139858183157504)>, <Thread(MyThread1, started 139858153768704)>]
i is: 2
2
[<_MainThread(MainThread, stopped 139858183157504)>, <Thread(MyThread1, started 139858153768704)>]
i is: 3
2
[<_MainThread(MainThread, stopped 139858183157504)>, <Thread(MyThread1, started 139858153768704)>]
i is: 4
2
[<_MainThread(MainThread, stopped 139858183157504)>, <Thread(MyThread1, started 139858153768704)>]
最佳答案
threading.activeCount() which returns the number of threads active (that were started with that module). [Source]
由于线程模块是构建在线程模块之上的纯 Python 模块,因此查看源代码非常容易。
这是active_count
的源代码
def activeCount():
"""Return the number of Thread objects currently alive.
The returned count is equal to the length of the list returned by
enumerate().
"""
with _active_limbo_lock:
return len(_active) + len(_limbo)
经过进一步调查,应该注意到有一个 _MainThread 实例存储在 _active 中(_active 和 _limbo 都是将线程名称映射到它们的实例的字典)。并在调用 _exitfunc
时从 _active 中删除。
这是 _MainThread 的源代码,
class _MainThread(Thread):
def __init__(self):
Thread.__init__(self, name="MainThread")
self._Thread__started.set()
self._set_ident()
with _active_limbo_lock:
_active[_get_ident()] = self
def _set_daemon(self):
return False
def _exitfunc(self):
self._Thread__stop()
t = _pickSomeNonDaemonThread()
if t:
if __debug__:
self._note("%s: waiting for other threads", self)
while t:
t.join()
t = _pickSomeNonDaemonThread()
if __debug__:
self._note("%s: exiting", self)
self._Thread__delete()
一旦 _exitfunc
被调用,_MainThread
等待所有非守护线程加入,然后调用 Thread._delete
,在本例中为 mangled到 __Thread_delete
,后者又从 _active
字典中删除 _MainThread
。
_exitfunc
被分配给第 1201 行的 _shutdown
。
_shutdown = _MainThread()._exitfunc
_shutdown
从 pythonrun.c 调用,然后由 Py_Finalize
调用。 Py_Finalize
由 Py_Exit 调用,退出主进程(此时只剩下守护进程)。
Exit the current process. This calls Py_Finalize() and then calls the standard C library function exit(status).
这是一个让您获得预期行为的示例。
import threading, time
def f():
time.sleep(1) #wait for the interpreter to "shutdown"
print threading.enumerate()
if __name__ == '__main__':
t = threading.Thread(target=f)
t.daemon = True
t.start()
threading._shutdown() #simulate an interpreter shutdown
另一个很棒的 answer 描述了线程是如何关闭的。
关于python - 事件线程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21653554/
我是一名优秀的程序员,十分优秀!