PyQT线程池可运行代码

本文介绍了如何在PyQt5环境中利用multiprocessing模块创建并管理子进程,以及ThreadPoolExecutor进行线程池的并发操作,展示了如何控制子进程数量和处理队列数据。
部署运行你感兴趣的模型镜像
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()  # 确保在退出程序时关闭线程池

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值