Guest User

Untitled

a guest
Jan 12th, 2016
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.16 KB | None | 0 0
  1. import time
  2. from threading import Thread
  3.  
  4. class CountdownTask:
  5.     def __init__(self):
  6.         self._running = True
  7.    
  8.     def terminate(self):
  9.         self._running = False
  10.    
  11.     def run(self, n, t):
  12.         while self._running and n > 0:
  13.             print('T-minus', n)
  14.             n -= 1
  15.             time.sleep(t)
  16.  
  17. countdown1 = CountdownTask()
  18. thread1 = Thread(target=countdown1.run, args=(10, 2))
  19.  
  20. countdown2 = CountdownTask()
  21. thread2 = Thread(target=countdown2.run, args=(10, 1))
  22.  
  23. thread1.start()
  24. thread2.start()
  25.  
  26. #######################
  27. from queue import Queue
  28.  
  29. # Object that singals shutdown
  30. _sentinel = object()
  31.  
  32. # A thread that produces data
  33. def producer(out_q, n):
  34.     while n > 0:
  35.         out_q.put(n)
  36.         time.sleep(1)
  37.         n -= 1
  38.     out_q.put(_sentinel)
  39.  
  40. # A thread that consumes data
  41. def consumer(in_q):
  42.     while True:
  43.         data = in_q.get()
  44.         if data is _sentinel:
  45.             print("Bye...")
  46.             in_q.put(_sentinel)
  47.             break
  48.         else:
  49.             print(data)
  50.  
  51. q = Queue()
  52. t1 = Thread(target=consumer, args=(q,))
  53. t2 = Thread(target=producer, args=(q, 10))
  54. t1.start()
  55. t2.start()
Advertisement
Add Comment
Please, Sign In to add comment