How to handle shared data between multiple threads?

98 views

How to handle shared data between multiple threads?

How to handle shared data between multiple threads?

solveurit24@gmail.com Changed status to publish February 13, 2025
0

Use threading.Lock to synchronize access.

import threading

lock = threading.Lock()
count = 0

def increment():
    global count
    with lock:
        count += 1

threads = []
for _ in range(10):
    thread = threading.Thread(target=increment)
    threads.append(thread)
    thread.start()

for thread in threads:
    thread.join()
print(count)  # Output: 10

solveurit24@gmail.com Changed status to publish February 13, 2025
0
You are viewing 1 out of 1 answers, click here to view all answers.