【发布时间】:2012-02-23 19:55:16
【问题描述】:
我正在尝试执行以下操作。
我有 8 个内核。
-
我执行 8 个进程如下,其中 core_aa 是将 url 加载到队列中的文件名
python threaded_crawl.py core_aa --max_async_count=20 --use_headers --verbose > /tmp/core_aa.out python threaded_crawl.py core_ab --max_async_count=20 --use_headers --verbose > /tmp/core_ab.out python threaded_crawl.py core_ac --max_async_count=20 --use_headers --verbose > /tmp/core_ac.out python threaded_crawl.py core_ad --max_async_count=20 --use_headers --verbose > /tmp/core_ad.out python threaded_crawl.py core_ae --max_async_count=20 --use_headers --verbose > /tmp/core_ae.out python threaded_crawl.py core_af --max_async_count=20 --use_headers --verbose > /tmp/core_af.out python threaded_crawl.py core_ag --max_async_count=20 --use_headers --verbose > /tmp/core_ag.out python threaded_crawl.py core_ah --max_async_count=20 --use_headers --verbose > /tmp/core_ah.out 如果进程是运行 20 个线程的线程应用程序,每个线程的任务是获取 url。如果我有例如60K url,我运行一个进程,作业完成,所有线程都存活到队列为空
如果我运行多个进程,我注意到线程开始缓慢死亡,例如每 1000 人死亡。idea os 将一个进程的 60K 拆分为 8。线程总数为 20*8
每个进程不共享数据。
既然一项工作是一项工作,为什么执行多个进程会杀死线程?
我该如何解决?
class ThreadClass(threading.Thread):
def __init__(self,parms={},proxy_list=[],user_agent_list=[],use_cookies=True,fn=None,verbose=False):
threading.Thread.__init__(self)
def run(self):
while page_queue.qsize()>0:
FETCH URLS....
for page in xrange(THREAD_LIMIT):
tc = ThreadClass(parms=parms,proxy_list=proxy_list,user_agent_list=user_agent_list,use_cookies=use_cookies,fn=fn,verbose=verbose)
tc.start()
while threading.activeCount()>=THREAD_LIMIT:
time.sleep(1)
while threading.activeCount()>1:
time.sleep(1)
我知道如何调试并且没有错误。鉴于我有以下情况,
while threading.activeCount()>1:
time.sleep(1)
一旦线程都死了,代码会继续,即使队列中还有剩余的项目,线程应该运行直到队列为空。
很困惑。
一旦活跃计数
【问题讨论】:
-
PS..对于我使用的每个线程 opener = urllib2.build_opener()。有关于文件描述符 c.f. 的讨论。 stackoverflow.com/questions/9308166/in-python-when-threads-die。这可能是原因吗?我没有打开文件,但我正在使用 urllib2 来获取网页。
-
PPS 当我添加以下代码以启动新线程时,如果最大线程数低于其工作的阈值 --> 而 threading.activeCount()>1: if threading.activeCount()
THREAD_LIMIT: ntc = THREAD_LIMIT - threading.activeCount() for i in xrange(ntc): tc = ThreadClass(parms=parms,proxy_list=proxy_list,user_agent_list=user_agent_list,use_cookies=use_cookies,fn=fn, verbose=verbose) tc.start() print "started a new thread" time.sleep(1) -
如果您愿意,可以edit您的问题并添加更多信息,这将比评论更清楚。
标签: python multithreading