Barrier Objects in Python

A Barrier in Python is a synchronization primitive that allows multiple threads to wait at a common point until all required threads reach that point, then releases them all simultaneously. This is useful for coordinating parallel tasks that need to synchronize at specific checkpoints.

Syntax

To create a barrier object, use the threading.Barrier class ?

threading.Barrier(parties, action=None, timeout=None)

Parameters

  • parties ? Number of threads that must reach the barrier before they are all released
  • action ? Optional callable executed by one thread when all threads reach the barrier
  • timeout ? Default timeout value for wait() method if no specific timeout is provided

Barrier Methods and Properties

Method/Property Description
parties Number of threads required to reach the barrier point
n_waiting Number of threads currently waiting at the barrier
broken Boolean indicating if the barrier is in broken state
wait(timeout=None) Wait until all threads reach the barrier or timeout occurs
reset() Reset barrier to empty state; waiting threads get BrokenBarrierError
abort() Put barrier in broken state; all wait() calls fail with BrokenBarrierError

Example

Here's a practical example simulating a race where all participants must reach the starting line before the race begins ?

import threading
import time
import random

# Create barrier for 4 threads
num_participants = 4
barrier = threading.Barrier(num_participants)

def racer(name):
    # Simulate different arrival times
    preparation_time = random.uniform(1, 3)
    time.sleep(preparation_time)
    
    print(f"{name} reached the starting line at {time.strftime('%H:%M:%S')}")
    
    # Wait for all racers to reach the barrier
    barrier.wait()
    
    print(f"{name} starts racing!")

# Create and start threads
participants = ["Alice", "Bob", "Charlie", "Diana"]
threads = []

print("Race preparation begins...")
print("-" * 30)

for participant in participants:
    thread = threading.Thread(target=racer, args=(participant,))
    threads.append(thread)
    thread.start()

# Wait for all threads to complete
for thread in threads:
    thread.join()

print("-" * 30)
print("All participants have started racing!")
Race preparation begins...
------------------------------
Bob reached the starting line at 14:23:45
Diana reached the starting line at 14:23:46
Alice reached the starting line at 14:23:47
Charlie reached the starting line at 14:23:47
Alice starts racing!
Bob starts racing!
Charlie starts racing!
Diana starts racing!
------------------------------
All participants have started racing!

Barrier with Action Function

You can specify an action function that executes when all threads reach the barrier ?

import threading
import time

def start_signal():
    print("? GO! All threads released simultaneously!")

# Create barrier with action function
barrier = threading.Barrier(3, action=start_signal)

def worker(worker_id):
    print(f"Worker {worker_id} is preparing...")
    time.sleep(1)  # Simulate work
    
    print(f"Worker {worker_id} reached barrier")
    barrier.wait()
    
    print(f"Worker {worker_id} continues working")

# Start 3 worker threads
threads = []
for i in range(3):
    thread = threading.Thread(target=worker, args=(i+1,))
    threads.append(thread)
    thread.start()

for thread in threads:
    thread.join()
Worker 1 is preparing...
Worker 2 is preparing...
Worker 3 is preparing...
Worker 1 reached barrier
Worker 2 reached barrier
Worker 3 reached barrier
? GO! All threads released simultaneously!
Worker 1 continues working
Worker 2 continues working
Worker 3 continues working

Key Points

  • Barriers are useful for synchronizing parallel computations that have multiple phases
  • All threads must reach the barrier before any can proceed
  • The action function (if provided) executes exactly once when all threads arrive
  • Barriers can be reused multiple times for different synchronization points
  • Use reset() or abort() to handle error conditions

Conclusion

Barrier objects provide an effective way to synchronize multiple threads at specific checkpoints. They're particularly useful in parallel algorithms where threads need to complete one phase before starting the next, ensuring coordinated execution across all participants.

Updated on: 2026-03-25T05:24:56+05:30

601 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements