Home  >  Q&A  >  body text

python - 如何多进程运行类函数

from multiprocessing import Pool

def a(num):
    print num

if __name__ == "__main__":
    pool = Pool(3)
    for i in range(10):
        pool.apply_async(a,args=(i,))
    pool.close()
    pool.join()

用进程池运行a这个函数,返回结果是正常的,但是假如这么写:

from multiprocessing import Pool


class adb():
    def a(self,num):
        print num


if __name__ == "__main__":
    pool = Pool(3)
    for i in range(10):
        pool.apply_async(adb().a,args=(i,))
    pool.close()
    pool.join()

则程序没有任何返回就结束了,请问这是怎么回事呢,有什么办法让后面这种写法也可以运行呢?

迷茫迷茫2720 days ago1661

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 09:50:18

    When using a class, the class object is not instantiated. Secondly, when calling a function, it needs to be called in the form of "class name.function name"

    Based on your modifications:

    • If you want to use class methods, then define class methods like this:

    class adb():
        @classmethod
        def a(self,num):
            print(num)
    • If you want to use class object methods, then initialize an object:

    if __name__ == "__main__":
        pool = Pool(3)
        a_obj = adb()
        for i in range(10):
            pool.apply_async(a_obj.a,args=(i,))
        pool.close()
        pool.join()

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 09:50:18

    pool.apply_async(adb().a,args=(i,))

    reply
    0
  • Cancelreply