What is thread synchronization in Python?

What is thread synchronization in Python?

a) Ensuring that threads execute in a specific sequence
b) Preventing multiple threads from accessing shared resources simultaneously
c) Allowing threads to communicate with each other
d) Running threads in parallel without any synchronization

Answer:

b) Preventing multiple threads from accessing shared resources simultaneously

Explanation:

Thread synchronization in Python refers to the technique of preventing multiple threads from accessing shared resources (such as variables, data structures, or files) simultaneously, which could lead to data corruption or inconsistent results. Synchronization ensures that only one thread can access the shared resource at a time.

import threading

counter = 0
lock = threading.Lock()

def increment_counter():
    global counter
    with lock:  # Acquire the lock before modifying the counter
        counter += 1

threads = []
for i in range(100):
    thread = threading.Thread(target=increment_counter)
    threads.append(thread)
    thread.start()

for thread in threads:
    thread.join()

print(f"Final counter value: {counter}")  # Output: Final counter value: 100

In this example, a lock is used to ensure that only one thread at a time can increment the counter variable. Without synchronization, multiple threads could modify the counter simultaneously, leading to incorrect results.

Thread synchronization is crucial in multithreaded applications where threads share resources, ensuring that the program behaves predictably and avoiding issues such as race conditions.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top