threading.current_thread()中的Dummy是什么?

问题描述 投票:1回答:1

我想了解这个How to use QThread correctly in pyqt with moveToThread()?中的代码

有以下部分:

mainwin.__init__         : MainThread, 140221684574016,
GenericWorker.__init__   : MainThread, 140221684574016,
GenericWorker.run        : Dummy-1, 140221265458944,
mainwin.addBatch         : Dummy-1, 140221265458944,
mainwin.add              : Dummy-1, 140221265458944,
mainwin.add              : Dummy-1, 140221265458944,
mainwin.add              : Dummy-1, 140221265458944,
mainwin.add              : Dummy-1, 140221265458944,
mainwin.add              : Dummy-1, 140221265458944,
mainwin.add              : Dummy-1, 140221265458944

我很感兴趣,Dummy -1元素究竟是什么,我的理解是这些是工作线程做的工作,但它们会永远“活着”吗?或者他们会自己收集垃圾。如果添加批量完成10k次,代码输出会有10k Dummy-1项吗?我只是问,因为我在使用子类Qthreads时看到了类似的输出,(在调试模式下运行代码时在Eclispe中使用Pydev)。

我不确定这是否意味着某种泄漏(线程泄漏)最终会占用大量资源。

python multithreading pyqt python-multithreading qthread
1个回答
0
投票

QThread不是Qt的一个线程,但它是一个用于处理每个操作系统的本机线程的类,python的线程模块如何,这在docs中提到:

QThread类提供了一种独立于平台的管理线程的方法。

因此,当使用threading.current_thread() python尝试获取本机线程,但正如docs指出(你也可以在source code中看到它):

返回当前Thread对象,对应于调用者的控制线程。如果未通过线程模块创建调用者的控制线程,则返回具有有限功能的虚拟线程对象。

因为QThread创建了一个未由线程模块处理的线程,这将返回一个代表该线程的虚拟线程。

它们存储在线程模块内的字典中,因此它们不会被GC删除,也不会泄漏。这在docs中提到:

有可能创建“虚拟线程对象”。这些是对应于“外部线程”的线程对象,它们是在线程模块外部启动的控制线程,例如直接来自C代码。虚拟线程对象具有有限的功能;他们总是被认为是活着的和守护的,不能加入()编辑。它们永远不会被删除,因为无法检测外来线程的终止。

source code

# Dummy thread class to represent threads not started here.
# These aren't garbage collected when they die, nor can they be waited for.
# If they invoke anything in threading.py that calls current_thread(), they
# leave an entry in the _active dict forever after.
# Their purpose is to return *something* from current_thread().
# They are marked as daemon threads so we won't wait for them
# when we exit (conform previous semantics).

因此总的来说,虚构元素提供了线程未处理的线程的信息,这些元素不受GC的影响,因为它们存储在字典中,因此不是内存泄漏。

© www.soinside.com 2019 - 2024. All rights reserved.