如何在Python eventlet中停止协同程序/线程

时间:2011-05-26 04:20:54

标签: python multithreading threadpool coroutine 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 个答案:

答案 0 :(得分:1)

最后一行永远不会被执行,因为你对q.get()的最后一次调用会永远阻塞,等待将某些东西添加到队列中。有几种方法可以解决这个问题,包括传递超时值来获取。我认为最干净的解决方案是在队列为空之前等待当前任务完成,然后再次尝试循环的另一次迭代:

while not q.empty():
    pool.spawn_n(download, q.get())
    if q.empty(): pool.waitall()