annotate CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/multiprocessing/heap.py @ 68:5028fdace37b

planemo upload commit 2e9511a184a1ca667c7be0c6321a36dc4e3d116d
author jpayne
date Tue, 18 Mar 2025 16:23:26 -0400
parents
children
rev   line source
jpayne@68 1 #
jpayne@68 2 # Module which supports allocation of memory from an mmap
jpayne@68 3 #
jpayne@68 4 # multiprocessing/heap.py
jpayne@68 5 #
jpayne@68 6 # Copyright (c) 2006-2008, R Oudkerk
jpayne@68 7 # Licensed to PSF under a Contributor Agreement.
jpayne@68 8 #
jpayne@68 9
jpayne@68 10 import bisect
jpayne@68 11 from collections import defaultdict
jpayne@68 12 import mmap
jpayne@68 13 import os
jpayne@68 14 import sys
jpayne@68 15 import tempfile
jpayne@68 16 import threading
jpayne@68 17
jpayne@68 18 from .context import reduction, assert_spawning
jpayne@68 19 from . import util
jpayne@68 20
jpayne@68 21 __all__ = ['BufferWrapper']
jpayne@68 22
jpayne@68 23 #
jpayne@68 24 # Inheritable class which wraps an mmap, and from which blocks can be allocated
jpayne@68 25 #
jpayne@68 26
jpayne@68 27 if sys.platform == 'win32':
jpayne@68 28
jpayne@68 29 import _winapi
jpayne@68 30
jpayne@68 31 class Arena(object):
jpayne@68 32 """
jpayne@68 33 A shared memory area backed by anonymous memory (Windows).
jpayne@68 34 """
jpayne@68 35
jpayne@68 36 _rand = tempfile._RandomNameSequence()
jpayne@68 37
jpayne@68 38 def __init__(self, size):
jpayne@68 39 self.size = size
jpayne@68 40 for i in range(100):
jpayne@68 41 name = 'pym-%d-%s' % (os.getpid(), next(self._rand))
jpayne@68 42 buf = mmap.mmap(-1, size, tagname=name)
jpayne@68 43 if _winapi.GetLastError() == 0:
jpayne@68 44 break
jpayne@68 45 # We have reopened a preexisting mmap.
jpayne@68 46 buf.close()
jpayne@68 47 else:
jpayne@68 48 raise FileExistsError('Cannot find name for new mmap')
jpayne@68 49 self.name = name
jpayne@68 50 self.buffer = buf
jpayne@68 51 self._state = (self.size, self.name)
jpayne@68 52
jpayne@68 53 def __getstate__(self):
jpayne@68 54 assert_spawning(self)
jpayne@68 55 return self._state
jpayne@68 56
jpayne@68 57 def __setstate__(self, state):
jpayne@68 58 self.size, self.name = self._state = state
jpayne@68 59 # Reopen existing mmap
jpayne@68 60 self.buffer = mmap.mmap(-1, self.size, tagname=self.name)
jpayne@68 61 # XXX Temporarily preventing buildbot failures while determining
jpayne@68 62 # XXX the correct long-term fix. See issue 23060
jpayne@68 63 #assert _winapi.GetLastError() == _winapi.ERROR_ALREADY_EXISTS
jpayne@68 64
jpayne@68 65 else:
jpayne@68 66
jpayne@68 67 class Arena(object):
jpayne@68 68 """
jpayne@68 69 A shared memory area backed by a temporary file (POSIX).
jpayne@68 70 """
jpayne@68 71
jpayne@68 72 if sys.platform == 'linux':
jpayne@68 73 _dir_candidates = ['/dev/shm']
jpayne@68 74 else:
jpayne@68 75 _dir_candidates = []
jpayne@68 76
jpayne@68 77 def __init__(self, size, fd=-1):
jpayne@68 78 self.size = size
jpayne@68 79 self.fd = fd
jpayne@68 80 if fd == -1:
jpayne@68 81 # Arena is created anew (if fd != -1, it means we're coming
jpayne@68 82 # from rebuild_arena() below)
jpayne@68 83 self.fd, name = tempfile.mkstemp(
jpayne@68 84 prefix='pym-%d-'%os.getpid(),
jpayne@68 85 dir=self._choose_dir(size))
jpayne@68 86 os.unlink(name)
jpayne@68 87 util.Finalize(self, os.close, (self.fd,))
jpayne@68 88 os.ftruncate(self.fd, size)
jpayne@68 89 self.buffer = mmap.mmap(self.fd, self.size)
jpayne@68 90
jpayne@68 91 def _choose_dir(self, size):
jpayne@68 92 # Choose a non-storage backed directory if possible,
jpayne@68 93 # to improve performance
jpayne@68 94 for d in self._dir_candidates:
jpayne@68 95 st = os.statvfs(d)
jpayne@68 96 if st.f_bavail * st.f_frsize >= size: # enough free space?
jpayne@68 97 return d
jpayne@68 98 return util.get_temp_dir()
jpayne@68 99
jpayne@68 100 def reduce_arena(a):
jpayne@68 101 if a.fd == -1:
jpayne@68 102 raise ValueError('Arena is unpicklable because '
jpayne@68 103 'forking was enabled when it was created')
jpayne@68 104 return rebuild_arena, (a.size, reduction.DupFd(a.fd))
jpayne@68 105
jpayne@68 106 def rebuild_arena(size, dupfd):
jpayne@68 107 return Arena(size, dupfd.detach())
jpayne@68 108
jpayne@68 109 reduction.register(Arena, reduce_arena)
jpayne@68 110
jpayne@68 111 #
jpayne@68 112 # Class allowing allocation of chunks of memory from arenas
jpayne@68 113 #
jpayne@68 114
jpayne@68 115 class Heap(object):
jpayne@68 116
jpayne@68 117 # Minimum malloc() alignment
jpayne@68 118 _alignment = 8
jpayne@68 119
jpayne@68 120 _DISCARD_FREE_SPACE_LARGER_THAN = 4 * 1024 ** 2 # 4 MB
jpayne@68 121 _DOUBLE_ARENA_SIZE_UNTIL = 4 * 1024 ** 2
jpayne@68 122
jpayne@68 123 def __init__(self, size=mmap.PAGESIZE):
jpayne@68 124 self._lastpid = os.getpid()
jpayne@68 125 self._lock = threading.Lock()
jpayne@68 126 # Current arena allocation size
jpayne@68 127 self._size = size
jpayne@68 128 # A sorted list of available block sizes in arenas
jpayne@68 129 self._lengths = []
jpayne@68 130
jpayne@68 131 # Free block management:
jpayne@68 132 # - map each block size to a list of `(Arena, start, stop)` blocks
jpayne@68 133 self._len_to_seq = {}
jpayne@68 134 # - map `(Arena, start)` tuple to the `(Arena, start, stop)` block
jpayne@68 135 # starting at that offset
jpayne@68 136 self._start_to_block = {}
jpayne@68 137 # - map `(Arena, stop)` tuple to the `(Arena, start, stop)` block
jpayne@68 138 # ending at that offset
jpayne@68 139 self._stop_to_block = {}
jpayne@68 140
jpayne@68 141 # Map arenas to their `(Arena, start, stop)` blocks in use
jpayne@68 142 self._allocated_blocks = defaultdict(set)
jpayne@68 143 self._arenas = []
jpayne@68 144
jpayne@68 145 # List of pending blocks to free - see comment in free() below
jpayne@68 146 self._pending_free_blocks = []
jpayne@68 147
jpayne@68 148 # Statistics
jpayne@68 149 self._n_mallocs = 0
jpayne@68 150 self._n_frees = 0
jpayne@68 151
jpayne@68 152 @staticmethod
jpayne@68 153 def _roundup(n, alignment):
jpayne@68 154 # alignment must be a power of 2
jpayne@68 155 mask = alignment - 1
jpayne@68 156 return (n + mask) & ~mask
jpayne@68 157
jpayne@68 158 def _new_arena(self, size):
jpayne@68 159 # Create a new arena with at least the given *size*
jpayne@68 160 length = self._roundup(max(self._size, size), mmap.PAGESIZE)
jpayne@68 161 # We carve larger and larger arenas, for efficiency, until we
jpayne@68 162 # reach a large-ish size (roughly L3 cache-sized)
jpayne@68 163 if self._size < self._DOUBLE_ARENA_SIZE_UNTIL:
jpayne@68 164 self._size *= 2
jpayne@68 165 util.info('allocating a new mmap of length %d', length)
jpayne@68 166 arena = Arena(length)
jpayne@68 167 self._arenas.append(arena)
jpayne@68 168 return (arena, 0, length)
jpayne@68 169
jpayne@68 170 def _discard_arena(self, arena):
jpayne@68 171 # Possibly delete the given (unused) arena
jpayne@68 172 length = arena.size
jpayne@68 173 # Reusing an existing arena is faster than creating a new one, so
jpayne@68 174 # we only reclaim space if it's large enough.
jpayne@68 175 if length < self._DISCARD_FREE_SPACE_LARGER_THAN:
jpayne@68 176 return
jpayne@68 177 blocks = self._allocated_blocks.pop(arena)
jpayne@68 178 assert not blocks
jpayne@68 179 del self._start_to_block[(arena, 0)]
jpayne@68 180 del self._stop_to_block[(arena, length)]
jpayne@68 181 self._arenas.remove(arena)
jpayne@68 182 seq = self._len_to_seq[length]
jpayne@68 183 seq.remove((arena, 0, length))
jpayne@68 184 if not seq:
jpayne@68 185 del self._len_to_seq[length]
jpayne@68 186 self._lengths.remove(length)
jpayne@68 187
jpayne@68 188 def _malloc(self, size):
jpayne@68 189 # returns a large enough block -- it might be much larger
jpayne@68 190 i = bisect.bisect_left(self._lengths, size)
jpayne@68 191 if i == len(self._lengths):
jpayne@68 192 return self._new_arena(size)
jpayne@68 193 else:
jpayne@68 194 length = self._lengths[i]
jpayne@68 195 seq = self._len_to_seq[length]
jpayne@68 196 block = seq.pop()
jpayne@68 197 if not seq:
jpayne@68 198 del self._len_to_seq[length], self._lengths[i]
jpayne@68 199
jpayne@68 200 (arena, start, stop) = block
jpayne@68 201 del self._start_to_block[(arena, start)]
jpayne@68 202 del self._stop_to_block[(arena, stop)]
jpayne@68 203 return block
jpayne@68 204
jpayne@68 205 def _add_free_block(self, block):
jpayne@68 206 # make block available and try to merge with its neighbours in the arena
jpayne@68 207 (arena, start, stop) = block
jpayne@68 208
jpayne@68 209 try:
jpayne@68 210 prev_block = self._stop_to_block[(arena, start)]
jpayne@68 211 except KeyError:
jpayne@68 212 pass
jpayne@68 213 else:
jpayne@68 214 start, _ = self._absorb(prev_block)
jpayne@68 215
jpayne@68 216 try:
jpayne@68 217 next_block = self._start_to_block[(arena, stop)]
jpayne@68 218 except KeyError:
jpayne@68 219 pass
jpayne@68 220 else:
jpayne@68 221 _, stop = self._absorb(next_block)
jpayne@68 222
jpayne@68 223 block = (arena, start, stop)
jpayne@68 224 length = stop - start
jpayne@68 225
jpayne@68 226 try:
jpayne@68 227 self._len_to_seq[length].append(block)
jpayne@68 228 except KeyError:
jpayne@68 229 self._len_to_seq[length] = [block]
jpayne@68 230 bisect.insort(self._lengths, length)
jpayne@68 231
jpayne@68 232 self._start_to_block[(arena, start)] = block
jpayne@68 233 self._stop_to_block[(arena, stop)] = block
jpayne@68 234
jpayne@68 235 def _absorb(self, block):
jpayne@68 236 # deregister this block so it can be merged with a neighbour
jpayne@68 237 (arena, start, stop) = block
jpayne@68 238 del self._start_to_block[(arena, start)]
jpayne@68 239 del self._stop_to_block[(arena, stop)]
jpayne@68 240
jpayne@68 241 length = stop - start
jpayne@68 242 seq = self._len_to_seq[length]
jpayne@68 243 seq.remove(block)
jpayne@68 244 if not seq:
jpayne@68 245 del self._len_to_seq[length]
jpayne@68 246 self._lengths.remove(length)
jpayne@68 247
jpayne@68 248 return start, stop
jpayne@68 249
jpayne@68 250 def _remove_allocated_block(self, block):
jpayne@68 251 arena, start, stop = block
jpayne@68 252 blocks = self._allocated_blocks[arena]
jpayne@68 253 blocks.remove((start, stop))
jpayne@68 254 if not blocks:
jpayne@68 255 # Arena is entirely free, discard it from this process
jpayne@68 256 self._discard_arena(arena)
jpayne@68 257
jpayne@68 258 def _free_pending_blocks(self):
jpayne@68 259 # Free all the blocks in the pending list - called with the lock held.
jpayne@68 260 while True:
jpayne@68 261 try:
jpayne@68 262 block = self._pending_free_blocks.pop()
jpayne@68 263 except IndexError:
jpayne@68 264 break
jpayne@68 265 self._add_free_block(block)
jpayne@68 266 self._remove_allocated_block(block)
jpayne@68 267
jpayne@68 268 def free(self, block):
jpayne@68 269 # free a block returned by malloc()
jpayne@68 270 # Since free() can be called asynchronously by the GC, it could happen
jpayne@68 271 # that it's called while self._lock is held: in that case,
jpayne@68 272 # self._lock.acquire() would deadlock (issue #12352). To avoid that, a
jpayne@68 273 # trylock is used instead, and if the lock can't be acquired
jpayne@68 274 # immediately, the block is added to a list of blocks to be freed
jpayne@68 275 # synchronously sometimes later from malloc() or free(), by calling
jpayne@68 276 # _free_pending_blocks() (appending and retrieving from a list is not
jpayne@68 277 # strictly thread-safe but under CPython it's atomic thanks to the GIL).
jpayne@68 278 if os.getpid() != self._lastpid:
jpayne@68 279 raise ValueError(
jpayne@68 280 "My pid ({0:n}) is not last pid {1:n}".format(
jpayne@68 281 os.getpid(),self._lastpid))
jpayne@68 282 if not self._lock.acquire(False):
jpayne@68 283 # can't acquire the lock right now, add the block to the list of
jpayne@68 284 # pending blocks to free
jpayne@68 285 self._pending_free_blocks.append(block)
jpayne@68 286 else:
jpayne@68 287 # we hold the lock
jpayne@68 288 try:
jpayne@68 289 self._n_frees += 1
jpayne@68 290 self._free_pending_blocks()
jpayne@68 291 self._add_free_block(block)
jpayne@68 292 self._remove_allocated_block(block)
jpayne@68 293 finally:
jpayne@68 294 self._lock.release()
jpayne@68 295
jpayne@68 296 def malloc(self, size):
jpayne@68 297 # return a block of right size (possibly rounded up)
jpayne@68 298 if size < 0:
jpayne@68 299 raise ValueError("Size {0:n} out of range".format(size))
jpayne@68 300 if sys.maxsize <= size:
jpayne@68 301 raise OverflowError("Size {0:n} too large".format(size))
jpayne@68 302 if os.getpid() != self._lastpid:
jpayne@68 303 self.__init__() # reinitialize after fork
jpayne@68 304 with self._lock:
jpayne@68 305 self._n_mallocs += 1
jpayne@68 306 # allow pending blocks to be marked available
jpayne@68 307 self._free_pending_blocks()
jpayne@68 308 size = self._roundup(max(size, 1), self._alignment)
jpayne@68 309 (arena, start, stop) = self._malloc(size)
jpayne@68 310 real_stop = start + size
jpayne@68 311 if real_stop < stop:
jpayne@68 312 # if the returned block is larger than necessary, mark
jpayne@68 313 # the remainder available
jpayne@68 314 self._add_free_block((arena, real_stop, stop))
jpayne@68 315 self._allocated_blocks[arena].add((start, real_stop))
jpayne@68 316 return (arena, start, real_stop)
jpayne@68 317
jpayne@68 318 #
jpayne@68 319 # Class wrapping a block allocated out of a Heap -- can be inherited by child process
jpayne@68 320 #
jpayne@68 321
jpayne@68 322 class BufferWrapper(object):
jpayne@68 323
jpayne@68 324 _heap = Heap()
jpayne@68 325
jpayne@68 326 def __init__(self, size):
jpayne@68 327 if size < 0:
jpayne@68 328 raise ValueError("Size {0:n} out of range".format(size))
jpayne@68 329 if sys.maxsize <= size:
jpayne@68 330 raise OverflowError("Size {0:n} too large".format(size))
jpayne@68 331 block = BufferWrapper._heap.malloc(size)
jpayne@68 332 self._state = (block, size)
jpayne@68 333 util.Finalize(self, BufferWrapper._heap.free, args=(block,))
jpayne@68 334
jpayne@68 335 def create_memoryview(self):
jpayne@68 336 (arena, start, stop), size = self._state
jpayne@68 337 return memoryview(arena.buffer)[start:start+size]