Last active
August 13, 2017 03:12
-
-
Save schedutron/8709662135564ebdaabf30df4025b463 to your computer and use it in GitHub Desktop.
A demo script for threading.Barrier synchronization primitive
This file contains hidden or 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 = 4 | |
b = Barrier(num) # 4 threads will need to pass this barrier to get released. | |
names = [“Harsh”, “Lokesh”, “George”, “Iqbal”] | |
def player(): | |
name = names.pop() | |
sleep(randrange(2, 5)) | |
print(“%s reached the barrier at: %s” % (name, ctime())) | |
b.wait() | |
threads = [] | |
print(“Race starts now…”) | |
for i in range(num): | |
threads.append(Thread(target=player)) | |
threads[-1].start() | |
for thread in threads: # Waits for the threads to complete before moving on with the main script. | |
thread.join() | |
print() | |
print(“Race over!”) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment