2012-02-23 56 views
2

我正在尝试执行以下操作。Python和线程 - 线程如果运行多个进程慢慢死去

  1. 我有8个内核。

  2. 我执行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 
    
  3. 如果每个proccess是运行20个线程,其任务是取一个URL的螺纹应用程序。如果我有例如60K URL和我运行一个proccess的工作与生活,直到队列中的所有线程完成是空

  4. 如果我运行一个以上的过程中,我注意到,线程开始慢慢例如死每1000思想OS一个死亡为一个proccess分裂60K至8线程的总numm​​ber为20 * 8

  5. 每个处理共享的任何数据。

因此,假设一个作业是一个作品,为什么要执行多个进程kill线程?

我该如何解决?

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) 

一旦线程都死了,代码继续即使有在排队时留下的线程应该运行,直到队列为空项。

很混乱。

一旦活性计数

+0

PS..for每个线程我使用开罐器= urllib2.build_opener()。有关于文件描述符c.f的喋喋不休http://stackoverflow.com/questions/9308166/in-python-when-threads-die。这可能是原因吗?我不打开文件,但我使用urllib2来获取网页。 – Tampa 2012-02-23 20:15:02

+0

我正在使用opener。关闭() – Tampa 2012-02-23 20:27:26

+0

PPS当我添加folling代码来启动一个新线程,如果最大线程数低于threashold它的工作 - > threading.activeCount()> 1: 如果threading.activeCount() THREAD_LIMIT: NTC = THREAD_LIMIT - threading.activeCount() 为i的x范围(NTC): TC = ThreadClass(PARMS = PARMS,proxy_list = proxy_list,user_agent_list = user_agent_list,use_cookies = use_cookies,FN = FN,详细=详细) tc.start() print“开始一个新的线程” time.sleep(1) – Tampa 2012-02-23 21:40:52

回答

3

.qsize()返回近似大小。请勿使用page_queue.qsize() > 0来检查队列是否为空。你可以使用while True: .. page_queue.get() ..和定点知道你什么时候完成,examplequeue.task_done()queue.join()组合。

.run()方法捕获例外,以避免过早地杀死一个线程。

请勿使用.activeCount()如果您需要n线程,则只需创建n线程。

让你的线程后台。能够在任何时候中断程序。

如果你的程序IO束缚你不需要多个进程。否则,您可以使用multiprocessing模块来管理多个进程,而不是手动启动它们。

+0

哇....谢谢...解决了很多问题。 – Tampa 2012-02-26 03:12:56