我一直在做一个我被分配去做的项目。它是关于某种 parking 场,现在进入的汽车自动生成(完成),我将它们放入“等待列表”(因为我必须稍后用 GUI 模块代表它们)以便以后分配在 parking 场的一个位置。然后他们必须离开 parking 场(也是随机的)
当我创建一个总是随机创建汽车的函数时出现问题,现在我不能调用任何其他函数,因为第一个函数正在循环。
问题是,有没有办法同时调用多个循环函数?
谢谢
请您参考如下方法:
the question is, is there a way to call several looping functions at the same time?
这是一个很好的问题,有几种方法可以做到这一点。
Threading可以让你的函数并发运行。线程之间的数据流应该使用 Queue module 来管理。 :
# Inter-thread communication
wait_to_park = Queue()
wait_to_exit = Queue()
# Start the simulation
tg = threading.Thread(target=generate_cars)
tp = threading.Thread(target=park_cars)
tu = threading.Thread(target=unpark_cars)
tg.start(); tp.start(); tu.start()
# Wait for simumlation to finish
tg.join()
wait_to_park.join()
tp.join()
wait_to_exit.join()
tu.join()
或者,您可以使用事件循环,例如 sched module协调事件。 Generators可能对此有所帮助——它们的工作方式类似于可以暂停和重新启动的功能。
