代码如下
# 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 个子线城应该怎么办?
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.