multiprocessing.value clear syntax?

前端 未结 2 1460
無奈伤痛
無奈伤痛 2020-12-29 10:34

I want to use multiprocessing.Value to use a variable in multiple processes, but the syntax is not clear on Python\'s documentation. Can anyone tell me what should I use as

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-29 11:22

    There is no special syntax for multiprocessing.Value, it's just a class like any other. The signature of the Value constructor is perfectly well described:

    multiprocessing.Value(typecode_or_type, *args[, lock])

    Return a ctypes object allocated from shared memory. By default the return value is actually a synchronized wrapper for the object.

    typecode_or_type determines the type of the returned object: it is either a ctypes type or a one character typecode of the kind used by the array module. *args is passed on to the constructor for the type.

    If lock is True (the default) then a new lock object is created to synchronize access to the value. If lock is a Lock or RLock object then that will be used to synchronize access to the value. If lock is False then access to the returned object will not be automatically protected by a lock, so it will not necessarily be “process-safe”.

    You even have some examples of its use afterwards. In particolar the typecode_or_type can be one of the typecodes that are listed in the documentation for the array module(e.g. 'i' for signed integer, 'f' for float etc.) or a ctypes type, like ctypes.c_int etc.

    If you want to have a Value containing a single letter you can do:

    >>> import multiprocessing as mp
    >>> letter = mp.Value('c', 'A')
    >>> letter
    
    >>> letter.value
    'A'
    

    Update

    The problem with your code is that the typecode 'c' means character not string. If you want to hold a string you can use the type ctypes.c_char_p:

    >>> import multiprocessing as mp
    >>> import ctypes
    >>> v = mp.Value('c', "Hello, World!")
    Traceback (most recent call last):
      File "", line 1, in 
      File "/usr/lib/python2.7/multiprocessing/__init__.py", line 253, in Value
        return Value(typecode_or_type, *args, **kwds)
      File "/usr/lib/python2.7/multiprocessing/sharedctypes.py", line 99, in Value
        obj = RawValue(typecode_or_type, *args)
      File "/usr/lib/python2.7/multiprocessing/sharedctypes.py", line 73, in RawValue
        obj.__init__(*args)
    TypeError: one character string expected
    >>> v = mp.Value(ctypes.c_char_p, "Hello, World!")
    >>> v
    
    >>> v.value
    'Hello, World!'
    

    For Python 3, use c_wchar_p instead of c_char_p

提交回复
热议问题