Created
July 16, 2019 01:55
-
-
Save eLtronicsVilla/606976e90542728ee105fc1c3ad815f2 to your computer and use it in GitHub Desktop.
Semaphore 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 BoundedSemaphore, Thread | |
max_items = 6 | |
""" | |
Consider 'container' as a container, with a capacity of 6 | |
items. Defaults to 1 item if 'max_items' is passed. | |
""" | |
container = BoundedSemaphore(max_items) | |
def producer(nloops): | |
for i in range(nloops): | |
time.sleep(random.randrange(2, 6)) | |
print(time.ctime(), end=": ") | |
try: | |
container.release() | |
print("item Produce kar rha.") | |
except ValueError: | |
print("Full ho gya, skipping.") | |
def consumer(nloops): | |
for i in range(nloops): | |
time.sleep(random.randrange(2, 5)) | |
print(time.ctime(), end=": ") | |
""" | |
In the following if statement we disable the default | |
blocking behaviour by passing False for the blocking flag. | |
""" | |
if container.acquire(False): | |
print("item Consume kar rha.") | |
else: | |
print("Empty box, skipping.") | |
threads = [] | |
nloops = random.randrange(3, 6) | |
print("Starting with %s items." % max_items) | |
threads.append(Thread(target=producer, args=(nloops,))) | |
threads.append(Thread(target=consumer, args=(random.randrange(nloops, nloops+max_items+2),))) | |
for thread in threads: # Starts all the threads. | |
thread.start() | |
for thread in threads: # Waits for threads to complete before moving on with the main script. | |
thread.join() | |
print("All operation done.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment