首頁  >  問答  >  主體

python - 当装饰器遇到multiprocessing, 出了点bug.

from multiprocessing import Pool

def with_app_context(need_new=False):
    def magic(func):
        app_store = {}
        def wrapper(*args, **kwargs):
            print 'inside', args, kwargs
            result = func(*args, **kwargs)
            return result

        return wrapper

    return magic


@with_app_context(need_new=True)
def func(k1, k2):
    print k1, k2
    return 'ret'


pool = Pool(processes=1)
pool.apply_async(func, args=('hi', 'yo'))
pool.close()
pool.join()

什么结果都不输出, 请问哪有bug?

天蓬老师天蓬老师2741 天前693

全部回覆(3)我來回復

  • 天蓬老师

    天蓬老师2017-04-18 10:32:27

    似乎是這個原因,函數裝飾器不可pickle
    可以看看這個:
    裝飾器與多進程以及Pickle

    • 擴充: Python MultiProcessing 使用心得

    回覆
    0
  • 阿神

    阿神2017-04-18 10:32:27

    我已經找到原因了:

    Traceback (most recent call last):
      File "wrapper.py", line 30, in <module>
        print ret.get()
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py", line 567, in get
        raise self._value
    cPickle.PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed
    

    子進程異常.

    回覆
    0
  • PHP中文网

    PHP中文网2017-04-18 10:32:27

    http://stackoverflow.com/ques...

    回覆
    0
  • 取消回覆