【问题标题】:python avoid busy wait in event processing threadpython避免事件​​处理线程中的忙等待
【发布时间】:2017-06-09 15:08:54
【问题描述】:

如何使用 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 实现类似于上述代码的功能?

【问题讨论】:

    标签: python multithreading python-asyncio eventqueue


    【解决方案1】:

    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_futureasyncio.Queue

    【讨论】:

      猜你喜欢
      • 2021-12-26
      • 2014-12-04
      • 2015-07-04
      • 1970-01-01
      • 2013-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多