from queue import Queue from threading import Thread
# A thread that produces data defproducer(out_q): whileTrue: # Produce some data ... out_q.put(data)
# A thread that consumes data defconsumer(in_q): whileTrue: # Get some data try: it = in_q.get_nowait() except queue.Empty as e1: continue if it isNone: break # Process the data ...
# Create the shared queue and launch both threads q = Queue() t1 = Thread(target=consumer, args=(q,)) t2 = Thread(target=producer, args=(q,)) t1.setDaemon(True) t1.start() t2.setDaemon(True) t2.start()
defrun(self, n): while self._running and n > 0: print('T-minus', n) n -= 1 time.sleep(5)
c = CountdownTask() t = Thread(target=c.run, args=(10,)) t.start() c.terminate() # Signal termination t.join() # Wait for actual termination (if needed)