Python: Making an asynchronous call within a recursive method in a new process

Viewed 24

I am trying to get an object instance to call a method asynchronously. The asynchronous call happens inside a recursive method of myClass as shown below:

class myClass():

  def __init__(self, id):
    self.id = id
    self.val = round(random.uniform(0, 1), 2)
    self.new_val = -1
    self.next = None
    self.pool = None

  def __str__(self):
    return "\nid:" + self.id + ", val:" + str(self.val) + ", new_val:" + str(self.new_val)

  def foo(self, x, y):
    if x > y:
      return round((x - y) * 2, 2)
    return round(x - y + 0.5, 2)

  def set_new_val(self, new_val):
    self.new_val = new_val

  def compare(self):  # recursive method
    print (self.id, "calling compare()")
    if self.next is None:
      self.new_val = round(random.uniform(0,1), 2)
    else: 
      self.pool.apply_async(self.foo, args=(self.val, self.next.val,), callback = self.set_new_val)
      # commenting the above line and uncommenting the line below gives the desired output
      # self.set_new_val(self.foo(self.val, self.next.val))  
      self.next.compare()  # recursive call

I then create a few objects of myClass and test the code.

import multiprocessing as mp

c1 = myClass('c1')
c2 = myClass('c2')
c3 = myClass('c3')

c1.pool = mp.Pool()
c2.pool = c3.pool = c1.pool
c1.next = c2
c2.next = c3

c1.compare()
print (c1, c2, c3)

Output:

c1 calling compare
c2 calling compare
c3 calling compare

id:c1, val:0.81, new_val:-1 
id:c2, val:0.04, new_val:-1 
id:c3, val:0.89, new_val:0.35

The code should ideally change the new_val of all the three objects, however, it only changes the new_val of c3. I am assuming it is because c1.compare() terminates before waiting for responses from the asynchronous calls made within c1.compare(). Any suggestions what changes need to be made to get the desired output/behavior?

0 Answers
Related