fork download
  1. import time
  2.  
  3. import queue
  4. import threading
  5.  
  6.  
  7. class LogQueue(queue.Queue):
  8.  
  9. def __init__(self, lock):
  10. self._lock = lock
  11. self.writes = 0
  12.  
  13. super(self.__class__, self).__init__()
  14.  
  15. def _dump(self):
  16. print('\n=======')
  17. with self._lock:
  18. while not self.empty():
  19. print('GOT', self.get())
  20. time.sleep(0.5)
  21. print('=======\n')
  22.  
  23. def put(self, *args, **kwargs):
  24. super(self.__class__, self).put(*args, **kwargs)
  25.  
  26. self.writes += 1
  27. if self.writes == 5:
  28. self.writes = 0
  29. self._dump()
  30.  
  31. # def __del__(self):
  32. # self._log.close()
  33.  
  34.  
  35. def writer(lock, log, condition):
  36. i = 0
  37. while True:
  38. if i == 15:
  39. return
  40.  
  41. if condition(i):
  42. with lock:
  43. log.put(i)
  44. print('PUT', i)
  45. time.sleep(0.1)
  46. i += 1
  47.  
  48.  
  49. lock = threading.RLock()
  50. log = LogQueue(lock)
  51.  
  52. threading.Thread(target=writer, args=(lock, log, lambda i: i % 2 == 0)).start()
  53. threading.Thread(target=writer, args=(lock, log, lambda i: i % 2 != 0)).start()
  54.  
Success #stdin #stdout 0.05s 28912KB
stdin
Standard input is empty
stdout
PUT 0
PUT 1
PUT 2
PUT 3

=======
GOT 0
GOT 1
GOT 2
GOT 3
GOT 4
=======

PUT 4
PUT 5
PUT 6
PUT 7
PUT 9

=======
GOT 5
GOT 6
GOT 7
GOT 9
GOT 8
=======

PUT 8
PUT 11
PUT 13
PUT 10
PUT 12

=======
GOT 11
GOT 13
GOT 10
GOT 12
GOT 14
=======

PUT 14