How to write the map sentence here to call array to calculate with ThreadPool module?
-
26-12-2019 - |
Question
I want to make a practice with module ThreadPool,to add 2 for every element in range(1,100).
from multiprocessing.pool import ThreadPool
array=range(1,100)
class test():
def myadd(self,x):
return(x+2)
do=ThreadPool(5)
do.map(test.myadd,array)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\Python34\lib\multiprocessing\pool.py", line 255, in map
return self._map_async(func, iterable, mapstar, chunksize).get()
File "D:\Python34\lib\multiprocessing\pool.py", line 594, in get
raise self._value
TypeError: exceptions must derive from BaseException
>>> do.map(test.myadd(self),array)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'self' is not defined
>>> do.map(test.myadd(),array)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: myadd() missing 2 required positional arguments: 'self' and 'x'
How to write the map sentence here to call array to calculate ? it is easy for me to do that with function such way:
from multiprocessing.pool import ThreadPool
array=range(1,100)
def myadd(x):
return(x+2)
do=ThreadPool(5)
do.map(myadd,array)
It works fine for me,when change the function into method in a class ,i am confused.
Solution
If you're going to make myadd
an instance method of the test
class, you have to actually instantiate the test
class to call myadd
:
from multiprocessing.pool import ThreadPool
class test():
def myadd(self,x):
return(x+2)
t = ThreadPool(5)
test_obj = test() # This gives you an instance of the `test` class
t.map(test_obj.my_add, range(1,100)) # Now you can call `myadd` on your instance
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow