如何在Python中创建循环并与之交互?

时间:2015-08-15 19:06:10

标签: python

不幸的是,这个问题更具概念性,但无论如何我想试一试。

我在循环上运行了一个aiohttp应用,从客户端获取输入并进行处理。

我希望有另一个循环,一个游戏循环,偶尔从另一个循环获取输入,然后前进。从概念上讲,似乎我有这两个(这不是我的实际代码,循环是通过asyncio调用的等等。这只是一个思考图):

# game loop
while True:
    action = yield from game.perform ???
    game_state.change(action)
    if game_state is "end":
        break

# socket loop
while True:
    message = yield from any_client
    if action in message:
         game.perform(action)
    for listener in clients: listener.send(message)

我有后者工作,但我在这方面很新,而且没有点击。

2 个答案:

答案 0 :(得分:1)

这听起来像是一个典型的生产者/消费者案例。您应该共享一个队列并将套接字循环放入其中,然后游戏循环从中获取。

Python内置队列有一个在等待生成内容时阻止的选项。 https://docs.python.org/2/library/queue.html#Queue.Queue.get

答案 1 :(得分:1)

import time
from threading import Thread
from queue import Queue

def worker():
    while True:
        time.sleep(1)
        item = queue.get()
        print(item)
        queue.task_done()

queue = Queue()
thread = Thread(target=worker)
thread.daemon = True
thread.start()

for item in [1, 2, 3]:
    print("Put it in")
    queue.put(item)

queue.join()       # block until all tasks are done

这就是诀窍。谢谢skyler!