-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path14_multithreading.py
More file actions
62 lines (52 loc) · 1.74 KB
/
Copy path14_multithreading.py
File metadata and controls
62 lines (52 loc) · 1.74 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
"""
14_multithreading.py
--------------------
Concept: Multithreading (Threading for I/O bound tasks)
Context: Running a Heartbeat Monitor while listening to a Simulated WebSocket.
Python Global Interpreter Lock (GIL) limits threads to one CPU content,
but they are great for I/O tasks like waiting for network data or user input.
"""
import threading
import time
import random
# Shared state
market_data = {"BTC": 60000}
is_running = True
# 1. Thread 1: The Worker (Simulated WebSocket Listener)
def data_stream_listener():
print("[Stream] Connected to Exchange Stream...")
while is_running:
time.sleep(1) # Simulate network latency
# Update shared memory
new_price = 60000 + random.randint(-500, 500)
market_data["BTC"] = new_price
print(f"[Stream] Updated BTC Price: ${new_price}")
print("[Stream] Connection Closed.")
# 2. Thread 2: The Monitor (Heartbeat / UI updater)
def heartbeat_monitor():
print("[Monitor] Service Started...")
while is_running:
time.sleep(2.5) # Checks every 2.5 seconds
current_price = market_data["BTC"]
print(f" >>> [Monitor] Heartbeat Check. Current BTC: ${current_price}")
print("[Monitor] Service Stopped.")
# Main Execution
if __name__ == "__main__":
# Create threads
t1 = threading.Thread(target=data_stream_listener)
t2 = threading.Thread(target=heartbeat_monitor)
# Start threads
t1.start()
t2.start()
# Let them run for 8 seconds
try:
time.sleep(8)
except KeyboardInterrupt:
pass
# Stop everything
print("\n[Main] Stopping threads...")
is_running = False
# Wait for threads to finish
t1.join()
t2.join()
print("[Main] All threads stopped. Exiting.")