进程 p.close和p.join的区别

p是指的进程

p.close()p.join()multiprocessing.Process类的两个方法,用于管理子进程的行为。

  1. p.close(): 这个方法用于关闭子进程。当调用p.close()后,子进程将不再接受新的任务。在子进程执行完当前任务后,它将自动退出。这个方法通常用于在主进程中关闭子进程,以防止子进程继续执行其他任务。

  2. p.join(): 这个方法用于等待子进程的结束。当调用p.join()后,主进程将阻塞,直到子进程执行完成并退出。在子进程执行期间,主进程将等待子进程的完成,然后再继续执行后续代码。这个方法通常用于确保主进程在子进程执行完毕后再继续执行后续操作。

总结起来,p.close()用于关闭子进程,而p.join()用于等待子进程的结束。这两个方法可以结合使用,以确保子进程在完成任务后被正确关闭,同时主进程能够等待子进程的完成后再继续执行。

实验后发现,如果不使用close()方法,而使用join()方法,那么GUI程序不退出,多次点击“启动子进程”按钮的话,就会创建越来越多的活跃的子进程。

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):
        import multiprocessing
        import threading
        print("进入子进程区域时")
        process_info = multiprocessing.current_process()
        print(f"当前进程数量: {multiprocessing.cpu_count()}")
        print(f"当前进程编号: {process_info.name}")

        # 打印当前线程数量和编号
        thread_info = threading.current_thread()
        print(f"当前线程数量: {threading.active_count()}")
        print(f"当前线程编号: {thread_info.name}")

        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()
 
            # 子进程完成后的逻辑
            result = self.q.get()
            print('主进程获取Queue数据:', result)
            p.close()
 
        thread = threading.Thread(target=run_child_process)
        thread.start()
 
if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()

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