Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion Lib/multiprocessing/heap.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#

import bisect
import ctypes
from collections import defaultdict
import mmap
import os
Expand Down Expand Up @@ -330,4 +331,9 @@ def __init__(self, size):

def create_memoryview(self):
(arena, start, stop), size = self._state
return memoryview(arena.buffer)[start:start+size]
# A view of arena.buffer alone cannot keep this allocation alive:
# the heap may recycle the block while the view is still in use.
# Keep the wrapper reachable through the buffer exporter.
exporter = (ctypes.c_ubyte * size).from_buffer(arena.buffer, start)
exporter._wrapper = self
return memoryview(exporter).cast('B')
25 changes: 25 additions & 0 deletions Lib/test/_test_multiprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4671,6 +4671,31 @@ def test_heap(self):
self.assertEqual(len(heap._allocated_blocks), 0, heap._allocated_blocks)
self.assertEqual(len(heap._len_to_seq), 0)

def test_memoryview_keeps_allocation_alive(self):
heap = multiprocessing.heap.BufferWrapper._heap
wrapper = multiprocessing.heap.BufferWrapper(8)
view = wrapper.create_memoryview()
view[:] = b"abcdefgh"
wrapper_ref = weakref.ref(wrapper)

# A derived view must keep the allocation alive even after the
# original view and wrapper have both gone away.
subview = view[2:6]
del view, wrapper
gc.collect()
self.assertIsNotNone(wrapper_ref())

# A second allocation must not overwrite the live view's data.
other = multiprocessing.heap.BufferWrapper(8)
other_view = other.create_memoryview()
other_view[:] = b"12345678"
self.assertEqual(bytes(subview), b"cdef")

del subview, other_view, other
gc.collect()
self.assertIsNone(wrapper_ref())
self.assertEqual(heap._n_frees, heap._n_mallocs)

def test_free_from_gc(self):
# Check that freeing of blocks by the garbage collector doesn't deadlock
# (issue #12352).
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Memoryviews returned by ``multiprocessing.heap.BufferWrapper.create_memoryview()``
now keep their shared-memory heap allocation alive until the view is released.
Loading