How to write the map sentence here to call array to calculate with ThreadPool module?

我怕爱的太早我们不能终老 提交于 2019-12-13 06:58:58

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/25075356/how-to-write-the-map-sentence-here-to-call-array-to-calculate-with-threadpool-mo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!