假设一个主程序创建 5 个线程,一次一个:
main.py
import threading
import time
from camera import Camera # this class inherits threading.Thread
# Initialize lock
lock = threading.RLock()
for i in range(5):
# Initialize camera threads
thread_1 = Camera(lock)
# Start videorecording
thread_1.start()
time.sleep(100)
# Signal thread to finish
thread_1.stop()
# Wait for thread to finish
thread_1.join()
del thread_1
当线程启动时,它会打印它的名称threading.currentThread().getName()
,产生以下输出:
Thread-1
Thread-2
Thread-3
Thread-4
Thread-5
为什么线程的名称不断增加?我假设Python会重置线程-xxx执行后删除每个线程后的数字del thread_1
.
这是预期的输出:
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
我认为您不能假设名称末尾的数字对应于当前活动线程的数量:
name是线程名称。默认情况下,唯一名称的构造形式为“Thread-N”,其中 N 是一个小十进制数。
Source: https://docs.python.org/3/library/threading.html#threading.Thread https://docs.python.org/3/library/threading.html#threading.Thread
例如,以下代码甚至不启动线程,而是立即删除它们:
import threading
for _ in range(3):
t = threading.Thread()
print(t.name)
del t
并且仍然打印:
Thread-1
Thread-2
Thread-3
Update:刚刚看了一下实施threading.py
在 CPython 中,其中Thread.__init__
calls _newname
如果没有给出名字。
# Helper to generate new thread names
_counter = _count().__next__
_counter() # Consume 0 so first non-main thread has id 1.
def _newname(template="Thread-%d"):
return template % _counter()
Source: https://github.com/python/cpython/blob/d0acdfcf345b44b01e59f3623dcdab6279de686a/Lib/threading.py#L738 https://github.com/python/cpython/blob/d0acdfcf345b44b01e59f3623dcdab6279de686a/Lib/threading.py#L738
该计数器只会不断增加。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)