[英]How to stop a coroutines / thread in Python eventlet
When I use the eventlet package to run a multi-coroutines task, even when the coroutines pool is empty, the program won't continue to run, but will get stuck in a loop.当我使用 eventlet package 运行多协程任务时,即使协程池为空,程序也不会继续运行,而是会卡在一个循环中。 Following is my code and the last row never get executed.
以下是我的代码,最后一行永远不会被执行。
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
The last row never gets executed because your final call to q.get() blocks forever, waiting for something to be added to the queue.最后一行永远不会执行,因为您对 q.get() 的最终调用会永远阻塞,等待将某些内容添加到队列中。 There are a few ways you could fix this, including passing a timeout value to get.
有几种方法可以解决这个问题,包括传递一个超时值来获取。 I think the cleanest solution is to wait for the current tasks to finish if the queue is empty before attempting another iteration of the loop again:
我认为最干净的解决方案是如果队列为空,则等待当前任务完成,然后再次尝试循环的另一次迭代:
while not q.empty():
pool.spawn_n(download, q.get())
if q.empty(): pool.waitall()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.