python - 如何多进程运行类函数
迷茫
迷茫 2017-04-18 09:48:18
0
2
1695
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()

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

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
Ty80

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()
巴扎黑

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!