子进程 子线程的关闭

子进程的关闭

from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
from multiprocessing import Process, Queue
import threading
import time
 
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.button = QPushButton('启动子进程', self)
        self.button.clicked.connect(self.start_child_process)
 
    def start_child_process(self):
        def run_child_process():
            p = MyProcess(self.q, self.data)
            p.start()
            p.join()
            p.close()  # 关闭子进程
 
            # 子进程完成后的逻辑
            result = self.q.get()
            print('主进程获取Queue数据:', result)
            self.q.close()  # 关闭队列
 
        thread = threading.Thread(target=run_child_process)
        thread.start()
 
        # 允许GUI事件循环继续处理其他事件
        while thread.is_alive():
            QApplication.processEvents()
 
if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()

子线程的关闭

import inspect
import ctypes
def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    tid = ctypes.c_long(tid)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
    _async_raise(thread.ident, SystemExit)

停止线程

stop_thread(myThread)

你可能感兴趣的:(多进程多线程,PyQt,多进程,多线程)