pyQt5线程池使用

#! /usr/bin/env python
#coding=utf-8
import threading

from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QProgressBar
import sys
import time

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("开始线程:" + self.name)
        tasks = []
        for counter in range(1,101):
            task=Tasks(counter)
            task.start()
            tasks.append(task)
        for t in tasks:
            t.notify()
            time.sleep(0.05)
        Tasks.wait()
        print ("退出线程:" + self.name)

class Thread(QtCore.QRunnable):
    
    def __init__(self,num):
       super(Thread,self).__init__()
       self.num=num
    def run(self):
       print("Running Thread #%d" % self.num)
       #time.sleep(2)
       #some say time.sleep will froze entire main thread(thus not recommended)

      QtCore.QThread.msleep(80)
       
#自定义信号槽如何把持http://www.cnblogs.com/codeio/archive/2011/08/30/2159030.html
class Tasks(QtCore.QObject):
    
    signal=QtCore.pyqtSignal(int)
    #signal must be declared outside the constructor but within class.
    def __init__(self,num):
       super(Tasks,self).__init__()
       self.pool=QtCore.QThreadPool.globalInstance()
       self.num=num
       self.signal.connect(proBar.setValue)
       #signal slot connection.watch out for parameter matching(type & count).    
    
    def start(self):
       threadIns=Thread(self.num)
       self.pool.start(threadIns)
    
    def notify(self):
        self.signal.emit(self.num)
    
    @staticmethod
    def wait():
       QtCore.QThreadPool.globalInstance().waitForDone()
       

       
if __name__=="__main__":
   App=QApplication(sys.argv)
   print(QtCore.QThread.currentThreadId())
    
   proBar=QProgressBar()
   proBar.setWindowTitle("Nuclear Launch Progression")
   proBar.setValue(0)
   proBar.setGeometry(200,500,1000,30)
   proBar.show()

   # 这里在子线程里异步启动QThreadPool,并等待线程池结束,如果不异步启动的话会阻塞ui主线程
   th = myThread(1, 'thread-1', 1)
   th.start()
   sys.exit(App.exec_())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值