PyQT线程池可运行代码

from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
from multiprocessing import Process, Queue
import time
from concurrent.futures import ThreadPoolExecutor

class MyProcess(Process):
    def __init__(self, q, data):
        super().__init__()
        self.q = q
        self.data = data

    def run(self):
        time.sleep(20)  # 模拟耗时操作
        print('子进程开始put数据')
        self.data.append('123')
        self.q.put(self.data)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.q = Queue()
        self.data = ['111', '222', '333']
        
        self.max_processes = 2  # 允许的最大子进程数
        self.current_processes = 0  # 当前运行的子进程数

        self.thread_pool = ThreadPoolExecutor(max_workers=2)  # 调整线程池的最大工作线程数

        self.process_button = QPushButton('启动子进程', self)
        self.process_button.clicked.connect(self.start_child_process)
        self.process_button.move(20, 20)

        self.print_button = QPushButton('打印数字', self)
        self.print_button.clicked.connect(self.start_print_number_thread)
        self.print_button.move(20, 60)

    def start_child_process(self):
        if self.current_processes < self.max_processes:
            self.current_processes += 1
            self.thread_pool.submit(self.run_child_process)
        else:
            print("已达到最大子进程数限制")

    def run_child_process(self):
        p = MyProcess(self.q, self.data)
        p.start()
        p.join()  # 等待子进程完成

        # 子进程完成后的逻辑
        self.current_processes -= 1
        result = self.q.get()
        print('主进程获取Queue数据:', result)

    def start_print_number_thread(self):
        self.thread_pool.submit(self.print_number)

    def print_number(self):
        time.sleep(5) 
        print("1")

    def close_thread_pool(self):
        self.thread_pool.shutdown(wait=True)

if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()
    window.close_thread_pool()  # 确保在退出程序时关闭线程池

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值