multiprocessing中Value和Array的实现原理都是在共享内存中创建ctypes()对象来达到共享数据的目的。两者实现方法大同小异,只是选用不同的ctypes数据类型而已。
1.Value
1.1 构造方法
Value(typecode_or_type: Union[str, Type[_CData]], *args: Any, lock: Union[bool, _LockLike] = ...)
typecode_or_type:定义ctypes()对象的类型,可以传Type code或者C Type,具体数据对照表见1.2
args:传递给typecode_or_type构造函数的参数
lock:默认为True,创建一个互斥锁来限制对Value的访问。如果传入一个锁,将用于同步。如果该值为False,Value的实例将不会被锁保护,即此时不是进程安全的。
1.2 支持的数据类型
| Type code | C Type | Python Type | Minimum size in bytes |
|---|---|---|---|
| 'b' | signed char | int | 1 |
| 'B' | unsigned char | int | 1 |
| 'u' | wchar_t | Unicode character | 2 |
| 'h' | signed short | int | 2 |
| 'H' | unsigned short | int | 2 |
| 'i' | signed int | int | 2 |
| 'I(大写的i)' | unsigned int | int | 2 |
| 'l(小写的l)' | signed long | int | 4 |
| 'L' | unsigned long | int | 4 |
| 'q' | signed long long | int | 8 |
| 'Q' | unsigned long long | int | 8 |
| 'f' | float | float | 4 |
| 'd' | double | float | 8 |
2.Array
2.1 构造方法
Array(typecode_or_type: Union[str, Type[_CData]], size_or_initializer: Union[int, Sequence[Any]], *, lock: Union[bool, _LockLike] = ...)
typecode_or_type:定义ctypes()对象的类型,可以传Type code或者C Type,具体数据对照表见2.2
size_or_initializer:如果其值是一个整数,则该值确定数组的长度,且数组被初始化为零。否则该值是用于初始化数组的序列,其长度决定数组的长度。
*:传递给typecode_or_type构造函数的参数
lock:默认为True,创建一个互斥锁来限制对Value的访问。如果传入一个锁,将用于同步。如果该值为False,Value的实例将不会被锁保护,即此时不是进程安全的。
3.使用实例
from multiprocessing import Process, Value, Array
def f(n, a):
n.value = 3.14
a[0] = 5
if __name__ == '__main__':
num = Value('d', 0.0)
arr = Array('i', range(10))
p = Process(target=f, args=(num, arr))
p.start()
p.join()
print(num.value)
print(arr[:])
result:
3.14
[5, 1, 2, 3, 4, 5, 6, 7, 8, 9]