daily pastebin goal
61%
SHARE
TWEET

Untitled

a guest Apr 16th, 2018 45 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from threading import Thread, Lock
  2. import time
  3. import random
  4.  
  5. queue = []
  6. lock = Lock()
  7.  
  8. class ProducerThread(Thread):
  9.     def run(self):
  10.         nums = range(5) #Will create the list [0, 1, 2, 3, 4]
  11.         global queue
  12.         while True:
  13.             num = random.choice(nums) #Selects a random number from list [0, 1, 2, 3, 4]
  14.             lock.acquire()
  15.             queue.append(num)
  16.             print ("Produced", num)
  17.             lock.release()
  18.             time.sleep(random.random())
  19.  
  20.  
  21. class ConsumerThread(Thread):
  22.     def run(self):
  23.         global queue
  24.         while True:
  25.             lock.acquire()
  26.             if not queue:
  27.                 print ("Nothing in queue, but consumer will try to consume")
  28.             num = queue.pop(0)
  29.             print ("Consumed", num)
  30.             lock.release()
  31.             time.sleep(random.random())
  32.  
  33.  
  34. ProducerThread().start()
  35. ConsumerThread().start()
RAW Paste Data
Top