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('结束测试')