2016-10-01 66 views
1

我正在写一个脚本,应该从一个非常大的数量或网站获取一些图片。第一次使用多线程,认为这是必需的,所以得到一个好的运行时。所以问题:脚本运行,但在看似随机数量的传递网站后,它不再继续。它不完全冻结寿,时间刚好从1/100秒的感觉上升。到几分钟左右,有时候这么长时间,只是关闭它而已。另外它似乎并不像某些网站特别负责,有时它会得到970个,仅有200个条目。这里的代码的相关部分:Python多线程冻结(?)随机

concurrent = 200 
q = Queue(concurrent * 2) 

def main(listPath, usagePath, idListPath): 
    [...] 
    for i in range(concurrent): 
     t = Thread(target=work) 
     t.daemon = True 
     t.start() 
    try: 
     for code in usedIDs: 
      q.put(code) 
     q.join() 

    except KeyboardInterrupt: 
     sys.exit(1) 


def work(): 
    while True: 
     code = q.get() 
     picture = getPicture(code) 
     if picture is None: 
      pass # todo: find other source or default 
     if not code in usage.keys(): 
      usage[code] = list() 
     usage[code].append(picture) 
     q.task_done() 

希望我得到了所有重要的代码。提前致谢!

+0

对于这类任务,我更愿意使用[multiprocessing.dummy](https://[ /docs.python.org/3/library/multiprocessing.html#module-multiprocessing.dummy)(它使用线程),因为它更易于使用。 – janbrohl

+0

您可能正在经历内存泄漏。当减速发生时,您是否查看过脚本的任何分析,甚至只是查看系统资源? – n8sty

+0

您似乎将图片存储在内存中。如果你的程序使用了太多的内存(超过你的内存容量),那么你的操作系统可能会使用[分页](https://en.wikipedia.org/wiki/Paging#Performance)到磁盘来提供所需的空间 - 这是非常缓慢的。 – janbrohl

回答

0

我的坏人,问题实际上是在getPicture函数中。无论如何感谢您的答案!