概述
通过multiprocessing实现多进程共享内存时,要用到Value和Array,定义如下:
Value:
Value(typecode_or_type, *args, lock=True, ctx=None)
Value:
Array(typecode_or_type, size_or_initializer, *, lock=True, ctx=None)
第一个参数typecode_or_type是指数据类型
因为共享内存要调用操作系统提供的函数,所以要指定数据类型
可指定 typecode 或 ctypes模块 中定义的类型
1.typecode
在multiprocessing库的sharedctypes.py文件中定义,截图如下:
typecode_to_type是dict类型,key是type code,value是ctypes模块定义的类型
typecode_to_type中type code与ctypes Type、C Type、Python Type关系如下:
| Type code | ctypes Type | C Type | Python Type |
|---|---|---|---|
| c | c_char | char | 1-character bytes object |
| u | c_wchar | wchar_t | 1-character string(可以是单个汉字) |
| b | c_byte | char | int |
| B | c_ubyte | unsigned char | int |
| h | c_short | short | int |
| H | c_ushort | unsigned short | int |
| i | c_int | int | int |
| l | c_long | long | int |
| L | c_ulong | unsigned long | int |
| f | c_float | float | float |
| d | c_double | double | float |
例子:
使用Value和Array时,指定typecode_or_type参数,用type code
from multiprocessing import Value
#i表示int型
num = Value('i',2000)
#修改值
num.value=3000
#取值
print(num.value)
#u表示字符,可以是汉字
text = Value('u','哈')
#修改值
text.value='呵'
#取值
print(text.value)
2.ctypes模块类型
见官方文档:
https://docs.python.org/3.6/library/ctypes.html#fundamental-data-types
注意:
- c_char表示字符,只能是一个英文字母
- c_wchar表示字符,可以是一个英文字母或者一个汉字
例子:
from multiprocessing import Value
import ctypes
#i表示int型
num = Value(ctypes.c_char,b'a')
#修改值
num.value=b'b'
#取值
print(num.value)
#布尔值
text = Value(ctypes.c_bool,False)
#修改值
text.value=True
#取值
print(text.value)