Skip to content

Instantly share code, notes, and snippets.

@eLtronicsVilla
Created July 16, 2019 02:10
Show Gist options
  • Save eLtronicsVilla/54ad91526038f364f4e99ae60b64b2da to your computer and use it in GitHub Desktop.
Save eLtronicsVilla/54ad91526038f364f4e99ae60b64b2da to your computer and use it in GitHub Desktop.
Barriers for synchronization mechanism
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