記憶體管理¶
總覽¶
在 Python 中,内存管理涉及到一个包含所有 Python 对象和数据结构的私有堆(heap)。这个私有堆的管理由内部的 Python 内存管理器(Python memory manager) 保证。Python 内存管理器有不同的组件来处理各种动态存储管理方面的问题,如共享、分割、预分配或缓存。
在最底层,一个原始内存分配器通过与操作系统的内存管理器交互,确保私有堆中有足够的空间来存储所有与 Python 相关的数据。在原始内存分配器的基础上,几个对象特定的分配器在同一堆上运行,并根据每种对象类型的特点实现不同的内存管理策略。例如,整数对象在堆内的管理方式不同于字符串、元组或字典,因为整数需要不同的存储需求和速度与空间的权衡。因此,Python 内存管理器将一些工作分配给对象特定分配器,但确保后者在私有堆的范围内运行。
It is important to understand that the management of the Python heap is performed by the interpreter itself and that the user has no control over it, even if she regularly manipulates object pointers to memory blocks inside that heap. The allocation of heap space for Python objects and other internal buffers is performed on demand by the Python memory manager through the Python/C API functions listed in this document.
为了避免内存破坏,扩展的作者永远不应该试图用 C 库函数导出的函数来对 Python 对象进行操作,这些函数包括: malloc()
, calloc()
, realloc()
和 free()
。这将导致 C 分配器和 Python 内存管理器之间的混用,引发严重后果,这是由于它们实现了不同的算法,并在不同的堆上操作。但是,我们可以安全地使用 C 库分配器为单独的目的分配和释放内存块,如下例所示:
PyObject *res;
char *buf = (char *) malloc(BUFSIZ); /* for I/O */
if (buf == NULL)
return PyErr_NoMemory();
...Do some I/O operation involving buf...
res = PyBytes_FromString(buf);
free(buf); /* malloc'ed */
return res;
In this example, the memory request for the I/O buffer is handled by the C library allocator. The Python memory manager is involved only in the allocation of the string object returned as a result.
然而,在大多数情况下,建议专门从 Python 堆中分配内存,因为后者由 Python 内存管理器控制。例如,当解释器扩展了用 C 写的新对象类型时,就必须这样做。使用 Python 堆的另一个原因是希望*通知* Python 内存管理器关于扩展模块的内存需求。即使所请求的内存全部只用于内部的、高度特定的目的,将所有的内存请求交给 Python 内存管理器能让解释器对其内存占用的整体情况有更准确的了解。因此,在某些情况下,Python 内存管理器可能会触发或不触发适当的操作,如垃圾回收、内存压缩或其他预防性操作。请注意,通过使用前面例子中所示的 C 库分配器,为 I/O 缓冲区分配的内存会完全不受 Python 内存管理器管理。
也參考
The PYTHONMALLOCSTATS
environment variable can be used to print
memory allocation statistics every time a new object arena is created, and
on shutdown.
原始内存接口¶
以下函数集封装了系统分配器。这些函数是线程安全的,不需要持有 GIL。
The default raw memory block allocator uses the following functions:
malloc()
, calloc()
, realloc()
and free()
; call
malloc(1)
(or calloc(1, 1)
) when requesting zero bytes.
3.4 版新加入.
-
void*
PyMem_RawMalloc
(size_t n)¶ Allocates n bytes and returns a pointer of type
void*
to the allocated memory, or NULL if the request fails.Requesting zero bytes returns a distinct non-NULL pointer if possible, as if
PyMem_RawMalloc(1)
had been called instead. The memory will not have been initialized in any way.
-
void*
PyMem_RawCalloc
(size_t nelem, size_t elsize)¶ Allocates nelem elements each whose size in bytes is elsize and returns a pointer of type
void*
to the allocated memory, or NULL if the request fails. The memory is initialized to zeros.Requesting zero elements or elements of size zero bytes returns a distinct non-NULL pointer if possible, as if
PyMem_RawCalloc(1, 1)
had been called instead.3.5 版新加入.
-
void*
PyMem_RawRealloc
(void *p, size_t n)¶ 将 p 指向的内存块大小调整为 n 字节。以新旧内存块大小中的最小值为准,其中内容保持不变,
If p is NULL, the call is equivalent to
PyMem_RawMalloc(n)
; else if n is equal to zero, the memory block is resized but is not freed, and the returned pointer is non-NULL.Unless p is NULL, it must have been returned by a previous call to
PyMem_RawMalloc()
,PyMem_RawRealloc()
orPyMem_RawCalloc()
.If the request fails,
PyMem_RawRealloc()
returns NULL and p remains a valid pointer to the previous memory area.
-
void
PyMem_RawFree
(void *p)¶ Frees the memory block pointed to by p, which must have been returned by a previous call to
PyMem_RawMalloc()
,PyMem_RawRealloc()
orPyMem_RawCalloc()
. Otherwise, or ifPyMem_Free(p)
has been called before, undefined behavior occurs.If p is NULL, no operation is performed.
内存接口¶
以下函数集,仿照 ANSI C 标准,并指定了请求零字节时的行为,可用于从Python堆分配和释放内存。
The default memory block allocator uses the following functions:
malloc()
, calloc()
, realloc()
and free()
; call
malloc(1)
(or calloc(1, 1)
) when requesting zero bytes.
警告
在使用这些函数时,必须持有 全局解释器锁(GIL) 。
-
void*
PyMem_Malloc
(size_t n)¶ Allocates n bytes and returns a pointer of type
void*
to the allocated memory, or NULL if the request fails.Requesting zero bytes returns a distinct non-NULL pointer if possible, as if
PyMem_Malloc(1)
had been called instead. The memory will not have been initialized in any way.
-
void*
PyMem_Calloc
(size_t nelem, size_t elsize)¶ Allocates nelem elements each whose size in bytes is elsize and returns a pointer of type
void*
to the allocated memory, or NULL if the request fails. The memory is initialized to zeros.Requesting zero elements or elements of size zero bytes returns a distinct non-NULL pointer if possible, as if
PyMem_Calloc(1, 1)
had been called instead.3.5 版新加入.
-
void*
PyMem_Realloc
(void *p, size_t n)¶ 将 p 指向的内存块大小调整为 n 字节。以新旧内存块大小中的最小值为准,其中内容保持不变,
If p is NULL, the call is equivalent to
PyMem_Malloc(n)
; else if n is equal to zero, the memory block is resized but is not freed, and the returned pointer is non-NULL.Unless p is NULL, it must have been returned by a previous call to
PyMem_Malloc()
,PyMem_Realloc()
orPyMem_Calloc()
.If the request fails,
PyMem_Realloc()
returns NULL and p remains a valid pointer to the previous memory area.
-
void
PyMem_Free
(void *p)¶ 释放 p 指向的内存块。除非 p 是
NULL
,否则它必须是之前调用PyMem_Malloc()
、PyMem_Realloc()
或PyMem_Calloc()
所返回的指针。否则,或在PyMem_Free(p)
之前已经调用过的情况下,未定义的行为会发生。If p is NULL, no operation is performed.
以下面向类型的宏为方便而提供。 注意 TYPE 可以指任何 C 类型。
-
TYPE*
PyMem_New
(TYPE, size_t n)¶ 与
PyMem_Malloc()
相同,但分配(n * sizeof(TYPE))
字节的内存。返回一个转换为TYPE*
的指针。内存不会以任何方式被初始化。
-
TYPE*
PyMem_Resize
(void *p, TYPE, size_t n)¶ Same as
PyMem_Realloc()
, but the memory block is resized to(n * sizeof(TYPE))
bytes. Returns a pointer cast toTYPE*
. On return, p will be a pointer to the new memory area, or NULL in the event of failure.这是一个 C 预处理宏, p 总是被重新赋值。请保存 p 的原始值,以避免在处理错误时丢失内存。
-
void
PyMem_Del
(void *p)¶ 与
PyMem_Free()
相同
此外,我们还提供了以下宏集用于直接调用 Python 内存分配器,而不涉及上面列出的 C API 函数。但是请注意,使用它们并不能保证跨 Python 版本的二进制兼容性,因此在扩展模块被弃用。
PyMem_MALLOC(size)
PyMem_NEW(type, size)
PyMem_REALLOC(ptr, size)
PyMem_RESIZE(ptr, type, size)
PyMem_FREE(ptr)
PyMem_DEL(ptr)
自定义内存分配器¶
3.4 版新加入.
-
PyMemAllocatorEx
¶ 用于描述内存块分配器的结构体。包含四个字段:
域 含义 void *ctx
作为第一个参数传入的用户上下文 void* malloc(void *ctx, size_t size)
分配一个内存块 void* calloc(void *ctx, size_t nelem, size_t elsize)
分配一个初始化为 0 的内存块 void* realloc(void *ctx, void *ptr, size_t new_size)
分配一个内存块或调整其大小 void free(void *ctx, void *ptr)
释放一个内存块 3.5 版更變: The
PyMemAllocator
structure was renamed toPyMemAllocatorEx
and a newcalloc
field was added.
-
PyMemAllocatorDomain
¶ 用来识别分配器域的枚举类。域有:
PYMEM_DOMAIN_RAW
: functionsPyMem_RawMalloc()
,PyMem_RawRealloc()
,PyMem_RawCalloc()
andPyMem_RawFree()
PYMEM_DOMAIN_MEM
: functionsPyMem_Malloc()
,PyMem_Realloc()
,PyMem_Calloc()
andPyMem_Free()
PYMEM_DOMAIN_OBJ
: functionsPyObject_Malloc()
,PyObject_Realloc()
,PyObject_Calloc()
andPyObject_Free()
-
void
PyMem_GetAllocator
(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)¶ 获取指定域的内存块分配器。
-
void
PyMem_SetAllocator
(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)¶ 设置指定域的内存块分配器。
The new allocator must return a distinct non-NULL pointer when requesting zero bytes.
对于
PYMEM_DOMAIN_RAW
域,分配器必须是线程安全的:当分配器被调用时,不持有 全局解释器锁 。如果新的分配器不是钩子(不调用之前的分配器),必须调用
PyMem_SetupDebugHooks()
函数在新分配器上重新安装调试钩子。
-
void
PyMem_SetupDebugHooks
(void)¶ Setup hooks to detect bugs in the following Python memory allocator functions:
PyMem_RawMalloc()
,PyMem_RawRealloc()
,PyMem_RawCalloc()
,PyMem_RawFree()
PyMem_Malloc()
,PyMem_Realloc()
,PyMem_Calloc()
,PyMem_Free()
PyObject_Malloc()
,PyObject_Realloc()
,PyObject_Calloc()
,PyObject_Free()
Newly allocated memory is filled with the byte
0xCB
, freed memory is filled with the byte0xDB
. Additional checks:- detect API violations, ex:
PyObject_Free()
called on a buffer allocated byPyMem_Malloc()
- detect write before the start of the buffer (buffer underflow)
- detect write after the end of the buffer (buffer overflow)
The function does nothing if Python is not compiled is debug mode.
Customize PyObject Arena Allocator¶
Python has a pymalloc allocator for allocations smaller than 512 bytes. This
allocator is optimized for small objects with a short lifetime. It uses memory
mappings called 「arenas」 with a fixed size of 256 KB. It falls back to
PyMem_RawMalloc()
and PyMem_RawRealloc()
for allocations larger
than 512 bytes. pymalloc is the default allocator used by
PyObject_Malloc()
.
The default arena allocator uses the following functions:
- Windows 上的
VirtualAlloc()
andVirtualFree()
, mmap()
和munmap()
,如果可用,- 否则,
malloc()
和free()
。
3.4 版新加入.
-
PyObjectArenaAllocator
¶ 用来描述一个 arena 分配器的结构体。这个结构体有三个字段:
域 含义 void *ctx
作为第一个参数传入的用户上下文 void* alloc(void *ctx, size_t size)
分配一块 size 字节的区域 void free(void *ctx, size_t size, void *ptr)
释放一块区域
-
PyObject_GetArenaAllocator
(PyObjectArenaAllocator *allocator)¶ 获取 arena 分配器
-
PyObject_SetArenaAllocator
(PyObjectArenaAllocator *allocator)¶ 设置 arena 分配器
例子¶
以下是来自 總覽 小节的示例,经过重写以使 I/O 缓冲区是通过使用第一个函数集从 Python 堆中分配的:
PyObject *res;
char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
if (buf == NULL)
return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyBytes_FromString(buf);
PyMem_Free(buf); /* allocated with PyMem_Malloc */
return res;
使用面向类型函数集的相同代码:
PyObject *res;
char *buf = PyMem_New(char, BUFSIZ); /* for I/O */
if (buf == NULL)
return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyBytes_FromString(buf);
PyMem_Del(buf); /* allocated with PyMem_New */
return res;
请注意在以上两个示例中,缓冲区总是通过归属于相同集的函数来操纵的。 事实上,对于一个给定的内存块必须使用相同的内存 API 族,以便使得混合不同分配器的风险减至最低。 以下代码序列包含两处错误,其中一个被标记为 fatal 因为它混合了两种在不同堆上操作的不同分配器。
char *buf1 = PyMem_New(char, BUFSIZ);
char *buf2 = (char *) malloc(BUFSIZ);
char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
...
PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */
free(buf2); /* Right -- allocated via malloc() */
free(buf1); /* Fatal -- should be PyMem_Del() */
除了旨在处理来自 Python 堆的原始内存块的函数之外, Python 中的对象是通过 PyObject_New()
, PyObject_NewVar()
和 PyObject_Del()
来分配和释放的。
这些将在有关如何在 C 中定义和实现新对象类型的下一章中讲解。