Reputation: 1292
This question is unfortunately a tad more conceptual, but I want to give it a shot anyway.
I have an aiohttp
app running on a loop, taking input from clients and handling it.
I want to have another loop, a game loop, that occasionally takes input from this other loop, and advances. Conceptually it seems like I have these two (this isn't my actual code, the loops are called via asyncio and such. this is just a thinking diagram):
# 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)
I have the latter working, but I'm very new at this, and something just isn't clicking.
Upvotes: 0
Views: 593
Reputation: 1292
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
This does the trick. Thanks skyler!
Upvotes: 1
Reputation: 1496
This sounds like a typical producer/consumer case. You should share a queue and have the socket loop put into it and the game loop get from it.
Python's built in queue has an option to block while waiting for something to be produced. https://docs.python.org/2/library/queue.html#Queue.Queue.get.
Upvotes: 1