python避免事件处理线程中的忙等待
如何使用asyncio避免事件使用者线程的繁忙等待? 我有一个主线程,它生成由其他线程处理的事件。我的事件线程有busy_wait,因为它正在尝试查看事件队列中是否有某些项python避免事件处理线程中的忙等待,python,multithreading,python-asyncio,eventqueue,Python,Multithreading,Python Asyncio,Eventqueue,如何使用asyncio避免事件使用者线程的繁忙等待? 我有一个主线程,它生成由其他线程处理的事件。我的事件线程有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(
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
从队列导入队列
从线程导入线程
导入线程
def do_工作(p):
打印(“打印p-%s%s”%(p,线程。当前线程())
def worker():
打印(“正在启动%s”%threading.current_thread())
虽然为True:#asyncio
只有在您使用IO时才有意义,例如运行一个。在下面的示例中,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()
另见和