from multiprocessing import Process, Queue
class Engine:
def __init__(self):
self.info = "Engine Info"
self.order_queue = Queue() # 创建一个用于接收订单的队列
self.orders = []
def get_info(self):
return self.info
def process_orders(self):
while True:
order_info = self.order_queue.get()
if not order_info: # 如果收到空数据,则退出循环
break
strategy_id, order = order_info
self.orders.append((strategy_id, order))
print(f"Engine: Order {order} received from Strategy #{strategy_id}. (Order processed)")
class Strategy(Process):
def __init__(self, engine, queue):
super().__init__()
self.engine = engine
self.queue = queue
def run(self):
while True:
data = self.queue.get()
if not data: # 如果数据为空(或者其他退出条件),则退出循环
break
self.on_data(data)
def on_data(self, data):
info = self.engine.get_info()
print(f"Strategy: Received data {data}, and info is {info}.")
# 假设生成订单
order = f"Order based on {data}"
self.engine.order_queue.put((self.pid, order)) # 将订单信息放入订单队列
if __name__ == "__main__":
engine = Engine()
# 创建并保存策略子进程及其各自的队列
queues = [Queue() for _ in range(3)]
strategies = [Strategy(engine, queue) for queue in queues]
for i in range(5): # 示例推送5次数据
for queue in queues:
queue.put(f"Data_{i}")
# 发送一个空数据到每个策略进程的队列中以结束它们
for queue in queues:
queue.put(None)
# 启动一个单独的进程来处理订单
order_processor = Process(target=engine.process_orders)
order_processor.start()
for strategy in strategies:
strategy.start()
for strategy in strategies:
strategy.join()
# 等待订单处理器完成所有订单处理
order_processor.join()
print("All strategies and order processor finished.")
print("Orders received by Engine:", engine.orders)