xuk13523892087
xuk13523892087
2018-11-29 07:00
采纳率: 50%
浏览 1.5k

python 进程池调用自定义类 没有反应 大佬们来看看

# coding: utf-8
import multiprocessing
import time
import os
class Count(object):
    def __init__(self, list):
        self.a = list[0]
        self.b = list[1]

    def run(self):
        if self.a >= 50:
            time.sleep(3)
            print(self.a,self.b)
        else:
            time.sleep(2)
            print("{}<50".format(self.a),self.b,os.getpid())

pool = multiprocessing.Pool(5)
list = [[35, 1], [67, 2], [45, 1], [77, 2], [55, 2]]

t1 = time.time()
for i in list:
    pool.apply_async(func=Count(i).run)
pool.close()
pool.join()
t2 = time.time()
print(t2-t1)


方法没有输出, 大佬们帮看下

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • xiao_bai_f
    西哇哇 2018-11-29 14:36
    已采纳

    定义入口函数

     if __name__ == '__main__':
        pool = multiprocessing.Pool(processes=3)
        list = [[35, 1], [67, 2], [45, 1], [77, 2], [55, 2]]
    
        for i in list:
            pool.apply_async(func=Count(i).run)
        pool.close()
        pool.join()
        # t2 = time.time()
        # print(t2-t1)
    

    你这个代码,我这个强迫症看着很难受呀~

    顺便帮你改了一下,代码 不谢~

    import multiprocessing
    import os
    
    
    class Count(object):
        def __init__(self, list):
            self.a, self.b = list
    
        def run(self):
            return (self.a, self.b) if self.a >= 50 else ("{}<50".format(self.a), self.b, os.getpid())
    
    
    if __name__ == '__main__':
        pool = multiprocessing.Pool(processes=5)
        params = [[35, 1], [67, 2], [45, 1], [77, 2], [55, 2]]
        res = [pool.apply_async(Count(val).run).get() for val in params if isinstance(val, list)]
        pool.close()
        pool.join()
        print(res)
    
    

    对了,还有一个小问题,变量名不要和python关键字一样~ list

    点赞 评论

相关推荐