-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueued_threads.py
56 lines (40 loc) · 1.39 KB
/
queued_threads.py
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
from threading import Thread
import time
import random
import queue
counter = 0
job_queue = queue.Queue()
counter_queue = queue.Queue()
def increment_manager():
global counter
while True:
increment = counter_queue.get() # this waits until an item is available and locks the queue
time.sleep(random.random())
old_counter = counter
time.sleep(random.random())
counter = old_counter + increment
time.sleep(random.random())
job_queue.put((f'New counter value {counter}', '------------'))
time.sleep(random.random())
counter_queue.task_done() # this unlocks the queue
# printer_manager and increment_manager run continuously because of the `daemon` flag.
Thread(target=increment_manager, daemon=True).start()
def printer_manager():
while True:
for line in job_queue.get():
time.sleep(random.random())
print(line)
job_queue.task_done()
# printer_manager and increment_manager run continuously because of the `daemon` flag.
Thread(target=printer_manager, daemon=True).start()
def increment_counter():
counter_queue.put(1)
time.sleep(random.random())
worker_threads = [Thread(target=increment_counter) for thread in range(10)]
for thread in worker_threads:
time.sleep(random.random())
thread.start()
for thread in worker_threads:
thread.join() # wait for it to finish
counter_queue.join() # wait for counter_queue to be empty
job_queue.join() # wait for job_queue to be empty