如何在这里写地图句子来调用使用ThreadPool模块计算的数组?

时间:2014-08-01 07:47:30

标签: python multithreading python-3.x threadpool python-multithreading

我想用模块ThreadPool进行练习,为范围内的每个元素(1,100)添加2。

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'

如何在这里写地图句子来调用数组来计算? 我很容易用这样的方式做到这一点:

from multiprocessing.pool import ThreadPool
array=range(1,100)
def  myadd(x):
    return(x+2)

do=ThreadPool(5)
do.map(myadd,array)

它对我来说很好,当在一个类中将函数更改为方法时,我很困惑。

1 个答案:

答案 0 :(得分:1)

如果您打算myadd test类的实例方法,则必须实际实例化test类以调用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