Python:如何在一个线程中断后添加新线程

2024-03-28 22:21:25 发布

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

我正在尝试创建线程循环,到目前为止代码还不错。但我有问题时,线程退出,因为一些异常。你知道吗

现在,我想知道如何在一个线程因异常退出后启动其他线程。我确实浏览了一下,但没有找到任何适用于这个复杂代码的示例。任何帮助都将是伟大的!你知道吗

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

这是我的密码:

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()

Tags: runnameselffordatadef线程thread
1条回答
网友
1楼 · 发布于 2024-03-28 22:21:25

这样的方法应该有用:

...
    # 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
...

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

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

相关问题 更多 >