forked from PacktPublishing/AdvancedPythonProgramming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample7.py
More file actions
74 lines (52 loc) · 1.92 KB
/
example7.py
File metadata and controls
74 lines (52 loc) · 1.92 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
72
73
74
# ch6/example7.py
from math import sqrt
import multiprocessing
class Consumer(multiprocessing.Process):
def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue
def run(self):
pname = self.name
while not self.task_queue.empty():
temp_task = self.task_queue.get()
print('%s processing task: %s' % (pname, temp_task))
answer = temp_task.process()
self.task_queue.task_done()
self.result_queue.put(answer)
class Task():
def __init__(self, x):
self.x = x
def process(self):
if self.x < 2:
return '%i is not a prime number.' % self.x
if self.x == 2:
return '%i is a prime number.' % self.x
if self.x % 2 == 0:
return '%i is not a prime number.' % self.x
limit = int(sqrt(self.x)) + 1
for i in range(3, limit, 2):
if self.x % i == 0:
return '%i is not a prime number.' % self.x
return '%i is a prime number.' % self.x
def __str__(self):
return 'Checking if %i is a prime or not.' % self.x
if __name__ == '__main__':
tasks = multiprocessing.JoinableQueue()
results = multiprocessing.Queue()
# spawning consumers with respect to the
# number cores available in the system
n_consumers = multiprocessing.cpu_count()
print('Spawning %i consumers...' % n_consumers)
consumers = [Consumer(tasks, results) for i in range(n_consumers)]
for consumer in consumers:
consumer.start()
# enqueueing jobs
my_input = [2, 36, 101, 193, 323, 513, 1327, 100000, 9999999, 433785907]
for item in my_input:
tasks.put(Task(item))
tasks.join()
for i in range(len(my_input)):
temp_result = results.get()
print('Result:', temp_result)
print('Done.')