Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- from threading import Thread
- class CountdownTask:
- def __init__(self):
- self._running = True
- def terminate(self):
- self._running = False
- def run(self, n, t):
- while self._running and n > 0:
- print('T-minus', n)
- n -= 1
- time.sleep(t)
- countdown1 = CountdownTask()
- thread1 = Thread(target=countdown1.run, args=(10, 2))
- countdown2 = CountdownTask()
- thread2 = Thread(target=countdown2.run, args=(10, 1))
- thread1.start()
- thread2.start()
- #######################
- from queue import Queue
- # Object that singals shutdown
- _sentinel = object()
- # A thread that produces data
- def producer(out_q, n):
- while n > 0:
- out_q.put(n)
- time.sleep(1)
- n -= 1
- out_q.put(_sentinel)
- # A thread that consumes data
- def consumer(in_q):
- while True:
- data = in_q.get()
- if data is _sentinel:
- print("Bye...")
- in_q.put(_sentinel)
- break
- else:
- print(data)
- q = Queue()
- t1 = Thread(target=consumer, args=(q,))
- t2 = Thread(target=producer, args=(q, 10))
- t1.start()
- t2.start()
Advertisement
Add Comment
Please, Sign In to add comment