0% found this document useful (0 votes)
5 views2 pages

Synchronization

The document outlines a Python program that uses threading to increment a shared counter while preventing race conditions through locks and semaphores. It allows a maximum of three threads to access the counter concurrently, ensuring safe modifications. After creating and starting ten threads, the program waits for all to complete and then prints the final value of the counter.

Uploaded by

symoiz2003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Synchronization

The document outlines a Python program that uses threading to increment a shared counter while preventing race conditions through locks and semaphores. It allows a maximum of three threads to access the counter concurrently, ensuring safe modifications. After creating and starting ten threads, the program waits for all to complete and then prints the final value of the counter.

Uploaded by

symoiz2003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

import threading

import time
import random

# Shared resource (e.g., a counter)


counter = 0

# Lock to prevent race conditions


lock = [Link]()

# Semaphore to allow a limited number of threads to access a resource at a


time
semaphore = [Link](3) # Only 3 threads can access the
resource at once

def increment_counter(thread_id):
global counter

# Acquiring the semaphore (limits concurrent access)


with semaphore:
print(f"Thread-{thread_id} is waiting for access...")
[Link]([Link](0.5, 1.5)) # Simulate work

# Acquiring lock to modify shared resource safely


with lock:
print(f"Thread-{thread_id} has acquired the lock.")
temp = counter
[Link]([Link](0.1, 0.5)) # Simulate processing
delay
counter = temp + 1
print(f"Thread-{thread_id} updated counter to {counter}")

print(f"Thread-{thread_id} has released the lock.")

# Creating multiple threads


threads = []
num_threads = 10 # Number of threads

for i in range(num_threads):
t = [Link](target=increment_counter, args=(i,))
[Link](t)
[Link]()

# Wait for all threads to complete


for t in threads:
[Link]()

print(f"\nFinal counter value: {counter}")

You might also like