代码如下
# coding: utf-8
import sys
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QWidget, QApplication
class Worker(QThread):
finish_signal = pyqtSignal(str)
def __init__(self):
super(Worker, self).__init__()
self.id = 0
self.li = []
def receive_ele(self, ele):
id, other = [int(i) for i in ele.split('_')]
if id != self.id:
return
self.li.append(other)
def run(self):
while 1:
if not self.li:
continue
li, self.li = self.li, []
ele = 0
for ele in li:
pass
self.finish_signal.emit("{}_{}".format(self.id, ele))
# QThread.sleep(1)
class Example(QWidget):
id_signal = pyqtSignal(str)
def __init__(self, parent=None):
super(Example, self).__init__(parent=parent)
# self.initUI()
self.data = [ i for i in range(1000)]
self.signals = [0]
self.initUI()
def initUI(self):
# Worker.finish_signal.connect(self.receive_finish)
for i in range(10):
t = Worker()
t.id = i+1
t.finish_signal.connect(self.receive_finish)
# self.signals.append(pyqtSignal(str))
self.id_signal.connect(t.receive_ele)
t.start()
ele = self.data.pop(0)
self.id_signal.emit("{}_{}".format(t.id, ele))
self.setGeometry(300, 300, 500, 500)
self.setWindowTitle("signal test")
print("show")
self.show()
def receive_finish(self, str):
id, num = str.split('_')
id, num = int(id), int(num)
if self.data:
ele = self.data.pop(0)
else:
ele = 0
print("thread:{}, finish num:{}, prepare:{}".format(id, num, ele))
if ele != 0:
self.id_signal.emit("{}_{}".format(id, ele))
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
开 10 个子线程,脚本启动不了,只能开一个子线程,这是为什么呀,我想要开 10 个或者 100 个子线城应该怎么办?
1
nicevar 2018-11-29 20:51:03 +08:00
你的代码怎么这么乱糟糟的,那个线程 t 是个局部变量,执行完后生命周期就结束了,线程里的代码都可能还没跑完,肯定直接报错的
|