I've created a program, which can be sum up to something like this:
from itertools import combinations
class Test(object):
def __init__(self, t2):
self.another_class_object = t2
def function_1(self,n):
a = 2
while(a <= n):
all_combs = combinations(range(n),a)
for comb in all_combs:
if(another_class_object.function_2(comb)):
return 1
a += 1
return -1
Function combinations
is imported from itertools
. Function_2
returns True
or False
depending on the input and is a method in another class object, e.g.:
class Test_2(object):
def __init__(self, list):
self.comb_list = list
def function_2(self,c):
return c in self.comb_list
Everything is working just fine. But now I want to change it a little bit and implement multiprocessing. I found this topic that shows an example of how to exit the script when one of the worker process determines no more work needs to be done. So I made following changes:
- added a definition of pool into
__init__
method:self.pool = Pool(processes=8)
created a callback function:
all_results = [] def callback_function(self, result): self.all_results.append(result) if(result): self.pool.terminate()
changed
function_1
:def function_1(self,n): a = 2 while(a <= n): all_combs = combinations(range(n),a) for comb in all_combs: self.pool.apply_async(self.another_class_object.function_2, args=comb, callback=self.callback_function) #self.pool.close() #self.pool.join() if(True in all_results): return 1 a += 1 return -1
Unfortunately, it does not work as I expected. Why? After debugging it looks like the callback function is never reached. I thought that it would be reached by every worker. Am I wrong? What can be the problem?