2012-05-21 19 views
1

當我運行這個python代碼時,發生了一些線程問題。我搜索互聯網,但我沒有找到答案。在使用python時gevent中發生線程異常

import urllib2 
from time import time 
import gevent 
import numpy as np 

tmp = np.loadtxt('data.txt', dtype=str) 
visit_list=tmp[:20] 

result_list =[] 

def visitUrl(u): 
    print 'start %s' %u 
    begin = time() 
    data = urllib2.urlopen(u).read() 
    print len(data) 
    print 'end-------- %s' %u 
    end = time() 
    print ('%s ::begin=%s ::end= %s::end-begin= %s' %(u, begin,end, end-begin)) 

for i in range(3): 
    reqs = [] 
    begin = time() 
    for u in visit_list: 
     start = time() 
     reqs.append(gevent.spawn(visitUrl, u)) 
     stop = time() 
     print ('%s $$$ %s' %(u, stop-start)) 
    #reqs = [gevent.spawn(visitUrl, u) for u in visit_list] 
    gevent.joinall(reqs) 
    end = time() 

    print 'ciclie %s=%s' %(i, end - begin) 
    result_list.append(end-begin) 

問題:

Exception KeyError: KeyError(4475468392,) in <module 'threading' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.pyc'> ignored 
+0

我跑你的代碼,它工作正常。你有哪個操作系統?哪個版本的python和gevent? data.txt中有哪些網址? –

回答

3

根據this thread主循環結束所有線程都完成其工作之前。

就叫gevent.shutdown()在年底或增加超時同時呼籲joinall

gevent.joinall(reqs, timeout=30) 
+0

非常感謝! – Djvu

+0

不客氣。如果我解決了您的問題,請考慮點擊此答案的複選標記,以補償我的effor。 ;-) –

相關問題