2015-08-15 53 views
0

不幸的是,这个问题稍微有些概念化,但我仍想给它一个镜头。如何在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) 

我有后者的工作,但我这很新鲜,而且不是点击。

+0

在您粘贴的代码中,只有第一个循环会运行。你需要使用线程,以便一次运行几个无限循环 – Nhor

+0

它的伪代码,我有asyncio循环运行在真实的东西 – RodericDay

+0

好吧,对不起,我的评论然后 – Nhor

回答

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!

+1

如果你使用'asyncio'的网络,为什么不还可以使用'asyncio'中的[Queue](https://docs.python.org/3/library/asyncio-queue.html),并且不需要线程? –