Skip to main content
 首页 » 编程设计

Python:如何在其中一个线程因错误而中断后添加新线程

2025年02月15日8EasonJim

我正在尝试创建线程循环,到目前为止代码还不错。但是当线程由于某些异常而退出时我遇到了问题。

现在我想弄清楚如何在一个线程因异常退出后启动其他线程。我确实四处浏览,但没有找到任何适用于此复杂代码的示例。任何帮助都会很棒!

如果线程停止并且队列不为空,则重新启动停止的线程并继续列表的其余部分。

这是我的代码:

some_list = [1,2,3,4,5,6,7,8] 
exitFlag = 0 
class threads(): 
    @staticmethod 
    def process_data(threadName, q,queueLock): 
        workQueue = q 
        while not exitFlag: 
            queueLock.acquire() 
            if not workQueue.empty(): 
                data = q.get() 
                queueLock.release() 
                print "%s processing %s" % (threadName, data) 
            else: 
                queueLock.release() 
            sleep(1) 
 
    def run_threads(self): 
        threadList = ["Thread-1", "Thread-2", "Thread-3"] 
        nameList = some_list 
        queueLock = threading.Lock() 
        workQueue = Queue.Queue(1000000) 
        threads = [] 
        threadID = 1 
 
        # Create new threads 
        for tName in threadList: 
            thread = myThread(threadID, tName, workQueue,queueLock) 
            thread.start() 
            threads.append(thread) 
            threadID += 1 
 
        # Fill the queue 
        queueLock.acquire() 
        for word in nameList: 
            workQueue.put(word) 
        queueLock.release() 
 
        # Wait for queue to empty 
        while not workQueue.empty(): 
            pass 
 
        # Notify threads it's time to exit 
        global exitFlag 
        exitFlag = 1 
 
        # Wait for all threads to complete 
        for t in threads: 
            t.join() 
        print "Exiting Main Thread" 
 
 
class myThread (threading.Thread,threads): 
    def __init__(self, threadID, name, q,queueLock): 
        self.thread = threading.Thread(target=self.run) 
        threading.Thread.__init__(self,target=self.run) 
        self.threadID = threadID 
        self.queueLock = queueLock 
        self.name = name 
        self.q = q 
 
    def run(self): 
       print "Starting " + self.name 
       threads.process_data(self.name, self.q,self.queueLock) 
       print "Exiting " + self.name 
 
threads().run_threads() 

请您参考如下方法:

像这样的东西应该可以工作:

... 
    # Wait for queue to empty 
    while not workQueue.empty(): 
        for (i, t) in enumerate(threads): 
            if not t.is_alive(): 
                print("Recreating thread " + t.name) 
                thread = myThread(threadID, threadList[i], workQueue,queueLock) 
                thread.start() 
                threads[i] = thread 
                threadID += 1 
... 

我建议将线程启动代码放入某个方法中,因为它现在将被复制并且难以维护。

这里的问题是您可能会“丢失”由致命线程从队列中弹出的数据。