2
votes

I'm trying to learn about map and apply_async in the following example (adapted from here).

from multiprocessing import Pool, Manager
from functools import partial
import time

def operate(number1=None, number2=None, op=None, timeout_list=None):
    if op == "+":
        return number1 + number2
    elif op == "-":
        time.sleep(1)
        return number1 - number2
    elif op == "/":
        time.sleep(6)
        return number1 / number2
    elif op == "*":
        time.sleep(10)
        return number1 * number2
    else:
        print("+, -, /, *")

timeout_list = Manager().list()
kwargs = {"number1":10, "number2":7, "timeout_list":timeout_list}

if __name__ == '__main__':
    ops = ["+", "+", "-", "*", "/", "+"]
    pool = Pool(processes=len(ops))
    result = pool.map(partial(operate, kwargs),ops)
    print(result.get(timeout=5))

I'm trying to do three things:

  1. pass op as a keyword to map after partially setting operate with number1 and number2 (but I'm currently getting an AttributeError: 'list' object has no attribute 'get')
  2. get the operations * and / to timeout and return * and / (respectively) as results from timing out in timeout_list
  3. how would I achieve the following with apply_async and what's the difference?
1

1 Answers

0
votes

Question: ... pass op as a keyword to map

You have, put the following in def operate(... to see what you do:

def operate(number1=None, number2=None, op=None, timeout_list=None):
    print('pid:{} operate({})'.format(os.getpid(), (number1, number2, op, timeout_list)))

>>>pid:4932 operate(({'number1': 10, 'number2': 7, 'timeout_list': <ListProxy object, typeid 'list' at 0xf6c0afac>}, 
                     '+', 
                     None, 
                     None)
                   )
  1. number1 == kwargs dict
  2. number2 == ops[x]
  3. op == None, because you use only 2 Parameters
  4. timeout_list == None, because you use only 2 Parameters

Question: ... partially setting operate with number1 and number2

You haven't, do the following to see what partial do:

print(partial(operate, kwargs))

>>>functools.partial(<function operate at 0xf70ed194>, 
                      {'number1': 10, 'number2': 7, 'timeout_list': <ListProxy object, typeid 'list' at 0xf70f38ec>})

Question: ... getting an AttributeError: 'list' object has no attribute 'get')
Read the AttributeError carefully!

.map(... returns a pure Python list not a result object!

 print(result)
>>>[None, None, None, None, None, None]

Question: 2. get the operations * and / to timeout and return ...

Unclear what you are asking?

Question: 3. how would I achieve the following with apply_async ...

Before you get further get Step 1 and 2 running.