如何在Python eventlet中停止协程/线程
当我使用eventlet这个包来运行多个协程任务时,即使协程池是空的,程序也不会继续运行,而是会卡在一个循环里。下面是我的代码,最后一行代码永远不会被执行。
import eventlet
global count
post_id=[]
last_id=0
def download(post_id):
global count
print "coroutines :",post_id
if count<last_id:
count=count+1
q.put(count) # put new coroutines in the queue
pool = eventlet.GreenPool()
q = eventlet.Queue()
for i in range(100,200):
post_id.append(i)
for i in range(0,5):
q.put(post_id[i]) # keep 6 coroutines in the pool
count=post_id[5]
last_id=200
while not q.empty() or pool.running()!=0:
pool.spawn_n(download,q.get()) #start corroutines
print "The end" #nerver reach to this line
1 个回答
1
最后一行代码永远不会被执行,因为你最后调用的 q.get() 会一直卡在那里,等着队列里有东西被添加进来。你可以通过几种方法来解决这个问题,比如给 get 方法设置一个超时时间。我觉得最简单的办法是,如果队列是空的,就等当前的任务完成后再尝试下一次循环:
while not q.empty():
pool.spawn_n(download, q.get())
if q.empty(): pool.waitall()