Question
import multiprocessing class ReductionConsumer(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 print('Using process %s...' % pname)
import multiprocessing
class ReductionConsumer(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
print('Using process %s...' % pname)
while True:
num1 = self.task_queue.get()
if num1 is None:
print('Exiting process %s.' % pname)
self.task_queue.task_done()
break
self.task_queue.task_done()
num2 = self.task_queue.get()
if num2 is None:
print('Reaching the end with process %s and number %i.' % (pname, num1))
self.task_queue.task_done()
self.result_queue.put(num1)
break
print('Running process %s on numbers %i and %i.' % (pname, num1, num2))
self.task_queue.task_done()
self.result_queue.put(num1 + num2)
def reduce_sum(array):
tasks = multiprocessing.JoinableQueue()
results = multiprocessing.JoinableQueue()
result_size = len(array)
n_consumers = multiprocessing.cpu_count()
for item in array:
results.put(item)
while result_size > 1:
tasks = results
results = multiprocessing.JoinableQueue()
consumers = [ReductionConsumer(tasks, results) for i in range(n_consumers)]
for consumer in consumers:
consumer.start()
for i in range(n_consumers):
tasks.put(None)
tasks.join()
result_size = result_size // 2 + (result_size % 2)
#print('-' * 40)
return results.get()
my_array = [i for i in range(20)]
result = reduce_sum(my_array)
print('Final result: %i.' % result)
This code is giving me a runtime error on visual studio on line 53
I try using idle, never gave me a result
> python example1.py Using process ReductionConsumer-1... Running process ReductionConsumer-1 on numbers 0 and 1. Using process ReductionConsumer-2... Running process ReductionConsumer-2 on numbers 2 and 3. Using process ReductionConsumer-3... [...Truncated for readability..] Exiting process ReductionConsumer-17. Exiting process ReductionConsumer-18. Exiting process ReductionConsumer-19. Using process ReductionConsumer-20... Exiting process ReductionConsumer-20. Final result: 190.
this is what it look like supposedly
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started