Advertisement
Guest User

ejemplo

a guest
Nov 13th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. #condition_tut.py
  2. import random, time
  3. from threading import Condition, Thread
  4. """
  5. 'condition' variable will be used to represent the availability of a produced
  6. item.
  7. """
  8. condition = Condition()
  9. box = []
  10. def producer(box, nitems):
  11.     for i in range(nitems):
  12.         time.sleep(random.randrange(2, 5))  # Sleeps for some time.
  13.         condition.acquire()
  14.         num = random.randint(1, 10)
  15.         box.append(num)  # Puts an item into box for consumption.
  16.         condition.notify()  # Notifies the consumer about the availability.
  17.         print("Produced:", num)
  18.         condition.release()
  19. def consumer(box, nitems):
  20.     for i in range(nitems):
  21.         condition.acquire()
  22.         condition.wait()  # Blocks until an item is available for consumption.
  23.         print("%s: Acquired: %s" % (time.ctime(), box.pop()))
  24.         condition.release()
  25. threads = []
  26. """
  27. 'nloops' is the number of times an item will be produced and
  28. consumed.
  29. """
  30. nloops = random.randrange(3, 6)
  31. for func in [producer, consumer]:
  32.     threads.append(Thread(target=func, args=(box, nloops)))
  33.     threads[-1].start()  # Starts the thread.
  34. for thread in threads:
  35.     """Waits for the threads to complete before moving on
  36.       with the main script.
  37.    """
  38.     thread.join()
  39. print("All done.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement