-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
71 lines (53 loc) · 1.62 KB
/
Copy pathexample.py
File metadata and controls
71 lines (53 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""Threading examples — locks, threads, and the GIL."""
import threading
import time
from concurrent.futures import ThreadPoolExecutor
counter = 0
counter_lock = threading.Lock()
def unsafe_increment():
global counter
for _ in range(100_000):
counter += 1
def safe_increment():
global counter
for _ in range(100_000):
with counter_lock:
counter += 1
def worker(name, delay):
print(f" Thread {name} starting")
time.sleep(delay)
print(f" Thread {name} done")
def demonstrate_race_condition():
global counter
counter = 0
threads = [threading.Thread(target=unsafe_increment) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"Unsafe counter (expected 400000): {counter}")
def demonstrate_lock():
global counter
counter = 0
threads = [threading.Thread(target=safe_increment) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"Safe counter (expected 400000): {counter}")
if __name__ == "__main__":
print("=== Basic threads ===")
threads = [threading.Thread(target=worker, args=(i, 0.1)) for i in range(3)]
for t in threads:
t.start()
for t in threads:
t.join()
print("\n=== Race condition ===")
demonstrate_race_condition()
print("\n=== Lock fixes race ===")
demonstrate_lock()
print("\n=== ThreadPoolExecutor ===")
with ThreadPoolExecutor(max_workers=3) as pool:
futures = [pool.submit(worker, f"pool-{i}", 0.05) for i in range(3)]
for f in futures:
f.result()