-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcode14.py
More file actions
43 lines (29 loc) · 1020 Bytes
/
code14.py
File metadata and controls
43 lines (29 loc) · 1020 Bytes
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
# code14.py
import time
import threading
class Producer(threading.Thread):
# This thread is implemented as a class
def __init__(self, queue):
super().__init__()
self.queue = queue
def run(self):
# We open the file using a context manager. We explain this in details
# in Chapter 10.
with open('raw_numbers.txt') as file:
for line in file:
values = tuple(map(int, line.strip().split(',')))
self.queue.append(values)
def consumer(queue):
# This thread is implemented as a function
with open('processed_numbers.txt', 'w') as file:
while len(queue) > 0:
numbers = queue.pop()
file.write('{}\n'.format(sum(numbers)))
# Simulates that the consumer is slower than the producer
time.sleep(0.001)
if __name__ == '__main__':
queue = MyDeque()
p = Producer(queue)
p.start()
c = threading.Thread(target=consumer, args=(queue,))
c.start()