Created
July 16, 2019 02:10
-
-
Save eLtronicsVilla/54ad91526038f364f4e99ae60b64b2da to your computer and use it in GitHub Desktop.
Barriers 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
from random import randrange | |
from threading import Barrier, Thread | |
from time import ctime, sleep | |
num = 5 | |
# 5 threads will need to pass this barrier to get released. | |
b = Barrier(num) | |
names = ["Brijesh", "Shubham", "Anup", "Kamesh"] | |
def player(): | |
name = names.pop() | |
sleep(randrange(2, 6)) | |
print("%s reached the barrier at: %s" % (name, ctime())) | |
b.wait() | |
threads = [] | |
print("Race conditions starts now") | |
for i in range(num): | |
threads.append(Thread(target=player)) | |
threads[-1].start() | |
""" | |
Following loop enables waiting for the threads to complete before moving on main. | |
""" | |
for thread in threads: | |
thread.join() | |
print() | |
print("Race over!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment