Perhaps i have not understood the barrier concept of threading. But i wrote a code that i want to learn it is a correct usage of barrier or not.
Here are the codes:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import random
import threading
def f(b):
time.sleep(random.randint(2, 10))
print("{} passed the barrier at: {}".format(threading.current_thread().getName(), time.ctime()))
b.wait()
barrier = threading.Barrier(3)
for i in range(3):
t = threading.Thread(target=f, args=(barrier,))
t.start()
Barrier Object - Python Multithreading. Barrier object is created by using Barrier class which is available in the threading module. This object can be used where we want a set of threads to wait for each other. For example, if we have two threads and we want both the threads to execute when both are ready.
Barrier Object - Python Multithreading Barrier object is created by using Barrier class which is available in the threading module. This object can be used where we want a set of threads to wait for each other. For example, if we have two threads and we want both the threads to execute when both are ready.
To define a barrier object, “threading. Barrier” is used. action = called by one of the threads when they are released. timeout = Default timeout value. In case no timeout value is specified for the wait (), this timeout value is used.
Each thread calls wait () function upon reaching the barrier. The barrier is responsible for keeping track of the number of wait () calls. If this number goes beyond the number of threads for which the barrier was initialized with, then the barrier gives a way to the waiting threads to proceed on with the execution.
The barrier sets up a count of threads that will wait together until that count is reached. With a small change in the test
import time
import random
import threading
def f(b):
time.sleep(random.randint(2, 10))
print("{} woke at: {}".format(threading.current_thread().getName(), time.ctime()))
b.wait()
print("{} passed the barrier at: {}".format(threading.current_thread().getName(), time.ctime()))
barrier = threading.Barrier(3)
for i in range(3):
t = threading.Thread(target=f, args=(barrier,))
t.start()
You can see that all threads wake from sleep at different times but return from wait
at the same time.
$ python3 o.py
Thread-2 woke at: Sun May 20 11:59:16 2018
Thread-3 woke at: Sun May 20 11:59:21 2018
Thread-1 woke at: Sun May 20 11:59:22 2018
Thread-1 passed the barrier at: Sun May 20 11:59:22 2018
Thread-2 passed the barrier at: Sun May 20 11:59:22 2018
Thread-3 passed the barrier at: Sun May 20 11:59:22 2018
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With