realsdx

producerconsumer.py

Nov 7th, 2019
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. import os
  2. import threading
  3. import time
  4.  
  5. BUFFEER_SIZE=10
  6. buffer=[]
  7. mutex=threading.Lock()
  8. notEmpty=threading.Semaphore(0)
  9.  
  10. def producer():
  11. id = threading.current_thread().name
  12. print("producer : {}".format(id))
  13. for i in range(BUFFEER_SIZE):
  14. data = "{}i:{}".format(id,i)
  15. with mutex:
  16. buffer.append(data)
  17. notEmpty.release()
  18.  
  19. def consumer():
  20. id=threading.current_thread().name
  21. for i in range(BUFFEER_SIZE):
  22. notEmpty.acquire()
  23. with mutex:
  24. data = buffer.pop()
  25. print("{} read: {}".format(id,data))
  26.  
  27. st=time.time()
  28. thread=[]
  29. c=threading.Thread(target = consumer)
  30. thread.append(c)
  31. p=threading.Thread(target = producer)
  32. thread.append(p)
  33. for i in thread:
  34. i.start()
  35. for i in thread:
  36. i.join()
  37. edt=time.time()
  38. print("Time taken:",(edt-st))
Add Comment
Please, Sign In to add comment