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

标签 python multithreading python-asyncio eventqueue

如何使用 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_futureasyncio.Queue .

关于python避免事件​​处理线程中的忙等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41834613/

相关文章:

java - 多线程和处理器的能力

python - 名称错误 : name 'asyncio' is not defined; In running discord bot

python - 减去下一行使用当前行,python 数据框

python - 如何在 Python 中获取 Linux 控制台窗口宽度

python - 使用 Python 加载 DLL 时出现错误 193

python - 为字母分配数值的更快方法?

multithreading - go指针多线程读写错误

java - DB事务还是Java DAO的方法同步?

python-3.x - 在多个消费者之间共享动态启动的工作线程

python - Asyncio 和 aiohttp 将所有 url 路径路由到处理程序