Created
July 16, 2019 02:03
-
-
Save eLtronicsVilla/933279398ae2e89511e2d147b6fa1b1b to your computer and use it in GitHub Desktop.
conditions creation for synchronization mechanism
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random, time | |
from threading import Condition, Thread | |
""" | |
'condition' variable will be used to represent the availability of a produced items. | |
""" | |
condition = Condition() | |
box = [] | |
def producer(box, nitems): | |
for i in range(nitems): | |
time.sleep(random.randrange(2, 6)) # Sleeps for some time. | |
condition.acquire() | |
num = random.randint(1, 15) | |
box.append(num) # Puts an item into box for consumption. | |
condition.notify() # Notifies the consumer about the availability. | |
print("Produced items:", num) | |
condition.release() | |
def consumer(box, nitems): | |
for i in range(nitems): | |
condition.acquire() | |
condition.wait() # Blocks until an item is available for consumption. | |
print("%s: Acquire : %s" % (time.ctime(), box.pop())) | |
condition.release() | |
threads = [] | |
""" | |
'nloops' is the number of times to be produced and consumed. | |
""" | |
nloops = random.randrange(3, 6) | |
for func in [producer, consumer]: | |
threads.append(Thread(target=func, args=(box, nloops))) | |
threads[-1].start() # Starts the thread. | |
for thread in threads: | |
"""Waits for the threads to complete before moving on to the main.""" | |
thread.join() | |
print("All operation done.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment