代码之家  ›  专栏  ›  技术社区  ›  Masoud Rahimi Chris

在线程类python中控制循环

  •  1
  • Masoud Rahimi Chris  · 技术社区  · 9 年前

    我想在python3中创建一个线程类。我想在一个类函数中控制一个无限循环。我想在类外的主函数中启动或停止这个循环。假设此代码:

    import threading
    from time import sleep
    class my_thread(threading.Thread):
        """Thread class with a stop() method. The thread itself has to check
        regularly for the stopped() condition."""
    
        def __init__(self):
            super(my_thread, self).__init__()
            self._stop_event = threading.Event()
    
        def stop(self):
            print("stopping the thread")
            self._stop_event.set()
    
        def stopped(self):
            return(self._stop_event.is_set())
    
        def run(self):
            print("running the thread")
            print("start function startt()")
            self._stop_event.clear()
            self.startt()
    
        def startt(self):
            print("it is going to wait forever")
            while not self.stopped():
                #wait forever, this part is going to run again and again
                pass
            print("This line never executes")
    
    
    if __name__+'__main__':
        thr=my_thread()
        thr.start()
        sleep(5)
        print("stopping the thread")
        thr.stop()
        # I cant start the thread and relative while loop again
        #thr.start()   
        print("Exiting the whole program")
    

    stop() 和 startt() 在我的主要例行程序中需要时,可以多次执行功能。 谢谢

    1 回复  |  直到 9 年前
        1
  •  1
  •   Kallz    9 年前

    首先,在my_thread类中使用Queue来管理由线程完成或调用的任务(方法)

    detail

    其次,添加一个类方法,以便可以将新方法或任务添加到队列中

    from queue import Queue
    # or
    # from multiprocessing import Queue
    class my_thread(threading.Thread):
        queue = Queue()
    
        @classmethod
        def add_task(cls,callable_task):
            cls.queue.put(callable_task)
    
        def startt(self):
            print("it is going to wait forever")
            while not self.stopped():
                #wait forever, this part is going to run again and again
                if not  self.queue.empty():
                      _m = self.queue.get()
                     # do what ever you want to do with _m
    
            print("This line never executes")
    

     Class my_thread(Threading.Thread)
         stop_event = threading.Event()
    
         @classmethod
         def stop_thread(cls)
             cls.stop_event.set()
    
         def startt(self):
             print("it is going to wait forever")
             cls = self.__class__
             while not cls.stop_event.is_set():
                 #wait forever, this part is going to run again and again
                 if not  self.queue.empty():
                     _m = self.queue.get()
                     # do what ever you want to do with _m
    
             print("This line never executes")
    

    现在呼吁停止therad

      my_thread.stop_thread()
    

    import threading
    import time
    class my_thread(threading.Thread):
        stop_event = threading.Event()
    
        @classmethod
        def stop_thread(cls):
            cls.stop_event.set()
    
        def run(self):
            print("running the thread")
            print("start function startt()")
            self.__class__.stop_event.clear()
            self.startt()
    
        def startt(self):
            print("it is going to wait forever")
            cls = self.__class__
            print cls.stop_event.is_set()
            while not cls.stop_event.is_set():
                pass
    
            print("This line never executes")
    
    a = my_thread()
    a.start()
    time.sleep(0.5)
    my_thread.stop_thread()
    print "\n\n\n"
    b = my_thread()
    b.start()
    time.sleep(0.5)
    my_thread.stop_thread()