Python Multiprocessing Locks

后端 未结 3 1683
暗喜
暗喜 2021-02-04 00:30

This multiprocessing code works as expected. It creates 4 Python processes, and uses them to print the numbers 0 through 39, with a delay after each print.

impor         


        
3条回答
  •  遇见更好的自我
    2021-02-04 00:56

    I think the reason is that the multiprocessing pool uses pickle to transfer objects between the processes. However, a Lock cannot be pickled:

    >>> import multiprocessing
    >>> import pickle
    >>> lock = multiprocessing.Lock()
    >>> lp = pickle.dumps(lock)
    Traceback (most recent call last):
      File "", line 1, in 
        lp = pickle.dumps(lock)
    ...
    RuntimeError: Lock objects should only be shared between processes through inheritance
    >>> 
    

    See the "Picklability" and "Better to inherit than pickle/unpickle" sections of https://docs.python.org/2/library/multiprocessing.html#all-platforms

提交回复
热议问题