-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathmain.py
More file actions
43 lines (29 loc) · 1.11 KB
/
Copy pathmain.py
File metadata and controls
43 lines (29 loc) · 1.11 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
import threading
from observers import ConsoleObserver
from observers import CountingObserver
from observers import MessageStorage
def produce(storage: MessageStorage, prefix: str, amount: int) -> None:
for index in range(amount):
storage.push_message(f"{prefix}-{index}")
def main() -> None:
storage = MessageStorage()
console = ConsoleObserver("console")
counter = CountingObserver()
storage.attach(console)
storage.attach(counter)
first = threading.Thread(target=produce, args=(storage, "hello", 3))
second = threading.Thread(target=produce, args=(storage, "world", 3))
first.start()
second.start()
first.join()
second.join()
print()
print("counter saw messages:", counter.count)
# Отписываем печать: источник не меняется, а поведение меняется.
storage.detach(console)
storage.push_message("nobody prints this one")
print("counter saw messages:", counter.count)
print()
print("в очереди осталось:", storage.read_messages())
if __name__ == "__main__":
main()