python 避免在事件处理线程中忙等待

python avoid busy wait in event processing thread

如何使用 asyncio 避免 busy_wait 来自事件消费者线程? 我有一个主线程,它生成由其他线程处理的事件。我的事件线程有 busy_wait,因为它试图查看事件队列中是否有某些项目...

from Queue import Queue

from threading import Thread
import threading

def do_work(p):
    print("print p - %s %s" % (p, threading.current_thread()))

def worker():
    print("starting %s" % threading.current_thread())
    while True: # <------------ busy wait
        item = q.get()
        do_work(item)
        time.sleep(1)
        q.task_done()

q = Queue()
t = Thread(target=worker)
t.daemon = True
t.start()

for item in range(20):
    q.put(item)

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

如何使用 asyncio 实现与上述代码类似的功能?

asyncio 只有在使用 IO 时才有意义,例如 运行 和 HTTP server or client。在以下示例中,asyncio.sleep() 模拟 I/O 调用。如果你有一堆 I/O 任务,它可以变得很简单:

import asyncio

import random

async def do_work(i):
    print("[#{}] work part 1".format(i))
    await asyncio.sleep(random.uniform(0.5, 2))
    print("[#{}] work part 2".format(i))
    await asyncio.sleep(random.uniform(0.1, 1))
    print("[#{}] work part 3".format(i))
    return "#{}".format(i)


loop = asyncio.get_event_loop()
tasks = [do_work(item + 1) for item in range(20)]
print("Start...")
results = loop.run_until_complete(asyncio.gather(*tasks))
print("...Done!")
print(results)
loop.close()

另见 ensure_future and asyncio.Queue