V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
noobpythoner
V2EX  ›  Python

Python 进程池在面向对象过程中,进程池无法调用实例方法

  •  
  •   noobpythoner · 2018-05-08 21:48:14 +08:00 · 3746 次点击
    这是一个创建于 2178 天前的主题,其中的信息可能已经有所发展或是发生改变。

    下列代码中,func 函数无法被 pool.apply_async 调用,这是什么情况?

    import time
    from multiprocessing.pool import Pool
    
    
    class Test:
        def __init__(self):
            self.pool = Pool(5)
    
        def func(self):
            time.sleep(0.2)
            print("1")
    
        def run(self):
            for i in range(10):
                self.pool.apply_async(self.func)  # 这里的 func 为什么不能进入执行?
    
            time.sleep(3)
            self.pool.close()
            self.pool.join()
    
    
    if __name__ == '__main__':
        t = Test()
        t.run()
    
    
    2 条回复    2018-05-08 22:48:44 +08:00
    justou
        2
    justou  
       2018-05-08 22:48:44 +08:00
    你把 func 改成 staticmethod 试试;

    再试试改成这样报什么错:

    import time
    from multiprocessing.pool import Pool

    class Test:
    def __init__(self):
    self.pool = Pool(5)

    def func(self):
    time.sleep(0.2)
    print("1")
    return 1

    def run(self):
    results = [self.pool.apply_async(self.func) for _ in range(10)]
    for res in results:
    print(res.get())

    time.sleep(3)
    self.pool.close()
    self.pool.join()


    if __name__ == '__main__':
    t = Test()
    t.run()

    再搜索下可能就很多收获了:)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5852 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 06:15 · PVG 14:15 · LAX 23:15 · JFK 02:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.