多进程
多进程(简单程序)
from multiprocessing import Process, Queue
class MyProcess(Process):
def __init__(self, q, i):
super().__init__()
self.q = q
self.i = i
def run(self):
print('子进程%s 开始put数据' % self.i)
self.q.put('我是%s 通过Queue通信' % self.i)
self.q.put('我是%s 通过Queue通信' % 2)
if __name__ == '__main__':
q = Queue()
process_list = []
p = MyProcess(q, 0)
p.start()
p.join()
print('主进程获取Queue数据')
print(q.get())
print(q.get())
print('结束测试')
主进程向子进程传递数据(简单程序)
from multiprocessing import Process, Queue
class MyProcess(Process):
def __init__(self, q, i, data):
super().__init__()
self.q = q
self.i = i
self.data = data
def run(self):
print('子进程%s 开始put数据' % self.i)
self.q.put(self.data[0]+1)
self.q.put(self.data[1]+1)
self.q.put(self.data[2]+1)
if __name__ == '__main__':
q = Queue()
data = [1, 2, 3] # 要传递的列表
process_list = []
p = MyProcess(q, 0, data)
p.start()
p.join()
print('主进程获取Queue数据')
print(q.get())
print(q.get())
print(q.get())
print('结束测试')
主进程向子进程传递数据(PyQT)
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
from multiprocessing import Process, Queue
class MyProcess(Process):
def __init__(self, q, data):
super().__init__()
self.q = q
self.data = data
def run(self):
print('子进程开始put数据')
self.q.put(self.data)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.q = Queue()
self.data = [1, 2, 3] # 要传递的列表
self.button = QPushButton('启动子进程', self)
self.button.clicked.connect(self.start_child_process)
def start_child_process(self):
p = MyProcess(self.q, self.data)
p.start()
p.join()
# 在这里可以处理子进程完成后的逻辑
result = self.q.get()
print('主进程获取Queue数据:', result)
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()