再次执行失败的线程

2024-09-27 21:27:28 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个脚本,它使用了大约50k个线程,但是一次只能运行10个。我使用线程库和BoundedSemaphore将线程限制为每次10个。在某些情况下,没有足够的内存供所有线程使用,但是处理所有线程是很重要的,所以我想重复那些由于内存不足而被杀死的线程。你知道吗

import some_other_script, threading


class myThread (threading.Thread):
    def __init__(self, item):
        threading.Thread.__init__(self)
        self.item = item
    def run(self):
        threadLimiter.acquire()
        some_other_script.method(self.item)
        somelist.remove(self.item)
        threadLimiter.release()


threadLimiter = threading.BoundedSemaphore(10)

somelist = ['50,000 Items','.....]
for item in somelist:
    myThread(item).start()

如您所见,到目前为止,我能想到的唯一想法是用somelist.remove(self.item)从每个线程的列表中删除已处理的项。(每个项目都是唯一的,在列表中只出现一次)。 我的想法是,我可以围绕for循环运行一个while循环,检查它是否仍然包含无法工作的项,因为在for循环完成之后,线程没有完成,所以列表不是空的。 我想做的是捕获那些失败的,因为系统内存不足,并再次执行它们(如果需要的话,还会再次执行)。你知道吗

事先非常感谢!你知道吗


Tags: self列表fordefscriptsomeitem线程
1条回答
网友
1楼 · 发布于 2024-09-27 21:27:28

这既解决了活动线程过多的问题,也解决了您的问题:

    def get_items():
          threads = threading.enumerate()
          items = set()
          for thr in threads:
              if isinstance(thr, myThread): items.add(thr.item)
          return items
    def manageThreads(howmany):
         while bigset:
             items = get_items()
             items_to_add = bigset.difference(items)
             while len(items) < howmany:
                 item = items_to_add.pop()
                 processor = myThread(item)
                 processor.start()
             with thread_done:    
                 thread_done.wait()
   thread_done = threading.Condition()
   bigset = set(["50,000 items", "..."])
   manageThreads(10)

mythread类运行方法:

def run(self):
    try:
        some_other_script.method(self.item)
        bigset.remove(self.item)
    finally:
        with thread_done:
            thread_done.notify()

Threading.enumerate()返回当前活动线程对象的列表。因此,manageThreads函数最初创建10个线程,然后等待一个线程完成,然后再次检查线程计数,依此类推。如果线程内存不足或在处理过程中发生另一个错误,它不会从bigset中删除该项,从而导致管理器将该项重新添加到另一个线程上。你知道吗

相关问题 更多 >

    热门问题