什么是假人线程.current_线程()?

2024-09-29 23:22:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图理解这个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元素到底是什么,我的理解是这些是工作线程在执行任务,但是它们会永远“活着”吗?或者他们会被自己收集垃圾。如果add batch执行了10k次,那么代码输出是否会有10k个Dummy-1项? 我之所以这么问,是因为我在使用子类Qthreads时看到了类似的输出(在Eclispe中使用Pydev,而在调试模式下运行代码)。在

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


Tags: to代码inaddinituse线程pyqt
1条回答
网友
1楼 · 发布于 2024-09-29 23:22:18

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

The QThread class provides a platform-independent way to manage threads.

因此,当使用threading.current_thread()时,python试图获取本机线程,但是正如docs所指出的那样(您也可以在source code中看到它):

Return the current Thread object, corresponding to the caller’s thread of control. If the caller’s thread of control was not created through the threading module, a dummy thread object with limited functionality is returned.

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

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

There is the possibility that “dummy thread objects” are created. These are thread objects corresponding to “alien threads”, which are threads of control started outside the threading module, such as directly from C code. Dummy thread objects have limited functionality; they are always considered alive and daemonic, and cannot be join()ed. They are never deleted, since it is impossible to detect the termination of alien threads.

{和}中的}:

# 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的影响,因为它们存储在字典中,因此不是内存泄漏。在

相关问题 更多 >

    热门问题