How to do it...

In this example, we simulate a run with three participants, Huey, Dewey, and Louie, in which a barrier is assimilated to that of a finish line.

Moreover, the race can end on its own when all three participants cross the finish line.

The barrier is implemented through the Barrier class, in which the number of threads to be completed must be specified as an argument to move to the next stage:

from random import randrange
from threading import Barrier, Thread
from time import ctime, sleep

num_runners = 3
finish_line = Barrier(num_runners)
runners = ['Huey', 'Dewey', 'Louie']

def runner():
name = runners.pop()
sleep(randrange(2, 5))
print('%s reached the barrier at: %s ' % (name, ctime()))
finish_line.wait()

def main():
threads = []
print('START RACE!!!!')
for i in range(num_runners):
threads.append(Thread(target=runner))
threads[-1].start()
for thread in threads:
thread.join()
print('Race over!')

if __name__ == "__main__":
main()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.135.224