产生这个疑问是因为,使用QThread创建的线程在Python的主线程里看不到子线程调用堆栈,而且用viztracer也看不到。
1.QThread的viztracer图表
2. 使用threading.Thread的viztracer图表
import threading
import time
from PyQt5 import QtCore
class Task(QtCore.QThread):
def __init__(self, idx):
super(__class__, self).__init__()
self.idx = idx
def run(self):
for i in range(20000):
print(f"{self.idx}:{i}")
def fun(idx):
for i in range(20000):
print(f"{idx}:{i}")
if __name__ == "__main__":
# threading.Thread
t1 = threading.Thread(target=fun, args=(1,), daemon=True)
t1.start()
t2 = threading.Thread(target=fun, args=(2,), daemon=True)
t2.start()
t3 = threading.Thread(target=fun, args=(3,), daemon=True)
t3.start()
t4 = threading.Thread(target=fun, args=(4,), daemon=True)
t4.start()
t5 = threading.Thread(target=fun, args=(5,), daemon=True)
t5.start()
time.sleep(5)
# QThread
t1 = Task(1)
t1.start()
t2 = Task(2)
t2.start()
t3 = Task(3)
t3.start()
t4 = Task(4)
t4.start()
t5 = Task(5)
t5.start()
time.sleep(5)
setText()
等。。。但setEnabled()
setChecked()
可以在线程里执行且不会报错,解决这一问题的办法是信号-槽机制,在槽函数里操作thd = threading.Thread(tartget=xxx, ...), thd.start()
的方式吧。以上为本人提供实验的表现得出的结论,不是官方结论,欢迎评论指出。