Files
2026-11-14 10:09:26 +03:00

43 lines
1.4 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Демонстрация состояния гонки и исправления через Lock."""
import threading
import time
class Counter:
def __init__(self):
self.value = 0
self.lock = threading.Lock()
def add_unsafe(self, repeats):
for _ in range(repeats):
old = self.value # чтение старого значения
time.sleep(0) # увеличиваем шанс переключения потоков
self.value = old + 1 # запись может затерять чужое обновление
def add_safe(self, repeats):
for _ in range(repeats):
with self.lock: # весь цикл «чтение — изменение — запись»
self.value += 1
def run(method, n_threads=4, repeats=2_000):
counter = Counter()
threads = [
threading.Thread(target=method, args=(counter, repeats))
for _ in range(n_threads)
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return counter.value, n_threads * repeats
if __name__ == "__main__":
unsafe, expected = run(Counter.add_unsafe)
safe, _ = run(Counter.add_safe)
print(f"Без Lock: {unsafe} из {expected}")
print(f"С Lock: {safe} из {expected}")
assert safe == expected