Python classes that inherit threads cannot end threads through flag bits
黄舟
黄舟 2017-05-18 11:02:22
0
1
834

I encountered such a problem when testing the producer-consumer model. After inheriting the thread, I added a mark mark

class Consumer(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self._queue = queue
        self.mark = True

    def run(self):
        while self.mark:
            msg = self._queue.get()
            if isinstance(msg, str) and msg == 'quit':
                break
            print("I'm a thread, and I received %s!!" % msg)

        print('Bye byes!')
def producer():
    q = queue.Queue()
    worker = Consumer(q)
    worker.start()  # 开启消费者线程
    start_time = time.time()
    while time.time() - start_time < 5:
        q.put('something at %s' % time.time())
        time.sleep(1)
    worker.mark = Flese
    worker.join()

I originally expected to use this flag to achieve thread end control, but the actual effect is that the program is stuck in worker.join()
and does not exit at all.

Excuse me, what is the reason for this?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(1)
伊谢尔伦
class Consumer(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self._queue = queue
        self.mark = True

    def run(self):
        while self.mark:
            try:
                msg = self._queue.get(block=False) # 非阻塞
                print("I'm a thread, and I received %s!!" % msg)
            except:pass
            
        print('self.mark',self.mark)
        print('Bye byes!')
        
def producer():
    q = queue.Queue()
    worker = Consumer(q)
    worker.start()  # 开启消费者线程
    start_time = time.time()
    while time.time() - start_time < 5:
        q.put('something at %s' % time.time())
        time.sleep(1)
    worker.mark = False
    worker.join()
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template