【发布时间】:2014-05-26 06:53:37
【问题描述】:
我试图弄清楚如何移植线程程序以使用asyncio。我有很多代码同步几个标准库Queues,基本上是这样的:
import queue, random, threading, time
q = queue.Queue()
def produce():
while True:
time.sleep(0.5 + random.random()) # sleep for .5 - 1.5 seconds
q.put(random.random())
def consume():
while True:
value = q.get(block=True)
print("Consumed", value)
threading.Thread(target=produce).start()
threading.Thread(target=consume).start()
一个线程创建值(可能是用户输入),另一个线程对它们进行处理。关键是这些线程在有新数据之前处于空闲状态,此时它们会醒来并对其进行处理。
我正在尝试使用 asyncio 来实现这种模式,但我似乎无法弄清楚如何让它“运行”。
我的尝试或多或少看起来像这样(并且根本不做任何事情)。
import asyncio, random
q = asyncio.Queue()
@asyncio.coroutine
def produce():
while True:
q.put(random.random())
yield from asyncio.sleep(0.5 + random.random())
@asyncio.coroutine
def consume():
while True:
value = yield from q.get()
print("Consumed", value)
# do something here to start the coroutines. asyncio.Task()?
loop = asyncio.get_event_loop()
loop.run_forever()
我尝试过使用协程的变体,不使用协程,在任务中包装东西,试图让它们创建或返回期货等。
我开始认为我对应该如何使用 asyncio 有错误的想法(也许这种模式应该以我不知道的不同方式实现)。 任何指针将不胜感激。
【问题讨论】:
-
你为什么要放弃线程以支持 asyncio?
-
@dmmd - 不离开,我一直在使用线程。然而,Asyncio 对于某些类型的问题很方便,特别是当它们涉及大量阻塞 I/O 时。在没有无限资源的系统(树莓派,“云”机器)上,有时 asyncio 可以用更少的努力完成同样的事情。
-
很高兴知道,谢谢。
标签: python python-3.x queue python-asyncio