Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1 | # |
| 2 | # Module which supports allocation of memory from an mmap |
| 3 | # |
| 4 | # multiprocessing/heap.py |
| 5 | # |
R. David Murray | d382066 | 2010-12-14 01:41:07 +0000 | [diff] [blame] | 6 | # Copyright (c) 2006-2008, R Oudkerk |
| 7 | # All rights reserved. |
| 8 | # |
| 9 | # Redistribution and use in source and binary forms, with or without |
| 10 | # modification, are permitted provided that the following conditions |
| 11 | # are met: |
| 12 | # |
| 13 | # 1. Redistributions of source code must retain the above copyright |
| 14 | # notice, this list of conditions and the following disclaimer. |
| 15 | # 2. Redistributions in binary form must reproduce the above copyright |
| 16 | # notice, this list of conditions and the following disclaimer in the |
| 17 | # documentation and/or other materials provided with the distribution. |
| 18 | # 3. Neither the name of author nor the names of any contributors may be |
| 19 | # used to endorse or promote products derived from this software |
| 20 | # without specific prior written permission. |
| 21 | # |
| 22 | # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND |
| 23 | # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 24 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| 25 | # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE |
| 26 | # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| 27 | # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS |
| 28 | # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) |
| 29 | # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| 30 | # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
| 31 | # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF |
| 32 | # SUCH DAMAGE. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 33 | # |
| 34 | |
| 35 | import bisect |
| 36 | import mmap |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 37 | import os |
| 38 | import sys |
| 39 | import threading |
| 40 | import itertools |
| 41 | |
| 42 | import _multiprocessing |
| 43 | from multiprocessing.util import Finalize, info |
| 44 | from multiprocessing.forking import assert_spawning |
| 45 | |
| 46 | __all__ = ['BufferWrapper'] |
| 47 | |
| 48 | # |
| 49 | # Inheirtable class which wraps an mmap, and from which blocks can be allocated |
| 50 | # |
| 51 | |
| 52 | if sys.platform == 'win32': |
| 53 | |
Brian Curtin | 6aa8bc3 | 2010-08-04 15:54:19 +0000 | [diff] [blame] | 54 | from _multiprocessing import win32 |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 55 | |
| 56 | class Arena(object): |
| 57 | |
| 58 | _counter = itertools.count() |
| 59 | |
| 60 | def __init__(self, size): |
| 61 | self.size = size |
| 62 | self.name = 'pym-%d-%d' % (os.getpid(), next(Arena._counter)) |
| 63 | self.buffer = mmap.mmap(-1, self.size, tagname=self.name) |
| 64 | assert win32.GetLastError() == 0, 'tagname already in use' |
| 65 | self._state = (self.size, self.name) |
| 66 | |
| 67 | def __getstate__(self): |
| 68 | assert_spawning(self) |
| 69 | return self._state |
| 70 | |
| 71 | def __setstate__(self, state): |
| 72 | self.size, self.name = self._state = state |
| 73 | self.buffer = mmap.mmap(-1, self.size, tagname=self.name) |
| 74 | assert win32.GetLastError() == win32.ERROR_ALREADY_EXISTS |
| 75 | |
| 76 | else: |
| 77 | |
| 78 | class Arena(object): |
| 79 | |
| 80 | def __init__(self, size): |
| 81 | self.buffer = mmap.mmap(-1, size) |
| 82 | self.size = size |
| 83 | self.name = None |
| 84 | |
| 85 | # |
| 86 | # Class allowing allocation of chunks of memory from arenas |
| 87 | # |
| 88 | |
| 89 | class Heap(object): |
| 90 | |
| 91 | _alignment = 8 |
| 92 | |
| 93 | def __init__(self, size=mmap.PAGESIZE): |
| 94 | self._lastpid = os.getpid() |
| 95 | self._lock = threading.Lock() |
| 96 | self._size = size |
| 97 | self._lengths = [] |
| 98 | self._len_to_seq = {} |
| 99 | self._start_to_block = {} |
| 100 | self._stop_to_block = {} |
| 101 | self._allocated_blocks = set() |
| 102 | self._arenas = [] |
Charles-François Natali | 778db49 | 2011-07-02 14:35:49 +0200 | [diff] [blame] | 103 | # list of pending blocks to free - see free() comment below |
| 104 | self._pending_free_blocks = [] |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 105 | |
| 106 | @staticmethod |
| 107 | def _roundup(n, alignment): |
| 108 | # alignment must be a power of 2 |
| 109 | mask = alignment - 1 |
| 110 | return (n + mask) & ~mask |
| 111 | |
| 112 | def _malloc(self, size): |
| 113 | # returns a large enough block -- it might be much larger |
| 114 | i = bisect.bisect_left(self._lengths, size) |
| 115 | if i == len(self._lengths): |
| 116 | length = self._roundup(max(self._size, size), mmap.PAGESIZE) |
| 117 | self._size *= 2 |
| 118 | info('allocating a new mmap of length %d', length) |
| 119 | arena = Arena(length) |
| 120 | self._arenas.append(arena) |
| 121 | return (arena, 0, length) |
| 122 | else: |
| 123 | length = self._lengths[i] |
| 124 | seq = self._len_to_seq[length] |
| 125 | block = seq.pop() |
| 126 | if not seq: |
| 127 | del self._len_to_seq[length], self._lengths[i] |
| 128 | |
| 129 | (arena, start, stop) = block |
| 130 | del self._start_to_block[(arena, start)] |
| 131 | del self._stop_to_block[(arena, stop)] |
| 132 | return block |
| 133 | |
| 134 | def _free(self, block): |
| 135 | # free location and try to merge with neighbours |
| 136 | (arena, start, stop) = block |
| 137 | |
| 138 | try: |
| 139 | prev_block = self._stop_to_block[(arena, start)] |
| 140 | except KeyError: |
| 141 | pass |
| 142 | else: |
| 143 | start, _ = self._absorb(prev_block) |
| 144 | |
| 145 | try: |
| 146 | next_block = self._start_to_block[(arena, stop)] |
| 147 | except KeyError: |
| 148 | pass |
| 149 | else: |
| 150 | _, stop = self._absorb(next_block) |
| 151 | |
| 152 | block = (arena, start, stop) |
| 153 | length = stop - start |
| 154 | |
| 155 | try: |
| 156 | self._len_to_seq[length].append(block) |
| 157 | except KeyError: |
| 158 | self._len_to_seq[length] = [block] |
| 159 | bisect.insort(self._lengths, length) |
| 160 | |
| 161 | self._start_to_block[(arena, start)] = block |
| 162 | self._stop_to_block[(arena, stop)] = block |
| 163 | |
| 164 | def _absorb(self, block): |
| 165 | # deregister this block so it can be merged with a neighbour |
| 166 | (arena, start, stop) = block |
| 167 | del self._start_to_block[(arena, start)] |
| 168 | del self._stop_to_block[(arena, stop)] |
| 169 | |
| 170 | length = stop - start |
| 171 | seq = self._len_to_seq[length] |
| 172 | seq.remove(block) |
| 173 | if not seq: |
| 174 | del self._len_to_seq[length] |
| 175 | self._lengths.remove(length) |
| 176 | |
| 177 | return start, stop |
| 178 | |
Charles-François Natali | 778db49 | 2011-07-02 14:35:49 +0200 | [diff] [blame] | 179 | def _free_pending_blocks(self): |
| 180 | # Free all the blocks in the pending list - called with the lock held. |
| 181 | while True: |
| 182 | try: |
| 183 | block = self._pending_free_blocks.pop() |
| 184 | except IndexError: |
| 185 | break |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 186 | self._allocated_blocks.remove(block) |
| 187 | self._free(block) |
Charles-François Natali | 778db49 | 2011-07-02 14:35:49 +0200 | [diff] [blame] | 188 | |
| 189 | def free(self, block): |
| 190 | # free a block returned by malloc() |
| 191 | # Since free() can be called asynchronously by the GC, it could happen |
| 192 | # that it's called while self._lock is held: in that case, |
| 193 | # self._lock.acquire() would deadlock (issue #12352). To avoid that, a |
| 194 | # trylock is used instead, and if the lock can't be acquired |
| 195 | # immediately, the block is added to a list of blocks to be freed |
| 196 | # synchronously sometimes later from malloc() or free(), by calling |
| 197 | # _free_pending_blocks() (appending and retrieving from a list is not |
| 198 | # strictly thread-safe but under cPython it's atomic thanks to the GIL). |
| 199 | assert os.getpid() == self._lastpid |
| 200 | if not self._lock.acquire(False): |
| 201 | # can't acquire the lock right now, add the block to the list of |
| 202 | # pending blocks to free |
| 203 | self._pending_free_blocks.append(block) |
| 204 | else: |
| 205 | # we hold the lock |
| 206 | try: |
| 207 | self._free_pending_blocks() |
| 208 | self._allocated_blocks.remove(block) |
| 209 | self._free(block) |
| 210 | finally: |
| 211 | self._lock.release() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 212 | |
| 213 | def malloc(self, size): |
| 214 | # return a block of right size (possibly rounded up) |
| 215 | assert 0 <= size < sys.maxsize |
| 216 | if os.getpid() != self._lastpid: |
| 217 | self.__init__() # reinitialize after fork |
| 218 | self._lock.acquire() |
Charles-François Natali | 778db49 | 2011-07-02 14:35:49 +0200 | [diff] [blame] | 219 | self._free_pending_blocks() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 220 | try: |
| 221 | size = self._roundup(max(size,1), self._alignment) |
| 222 | (arena, start, stop) = self._malloc(size) |
| 223 | new_stop = start + size |
| 224 | if new_stop < stop: |
| 225 | self._free((arena, new_stop, stop)) |
| 226 | block = (arena, start, new_stop) |
| 227 | self._allocated_blocks.add(block) |
| 228 | return block |
| 229 | finally: |
| 230 | self._lock.release() |
| 231 | |
| 232 | # |
| 233 | # Class representing a chunk of an mmap -- can be inherited |
| 234 | # |
| 235 | |
| 236 | class BufferWrapper(object): |
| 237 | |
| 238 | _heap = Heap() |
| 239 | |
| 240 | def __init__(self, size): |
| 241 | assert 0 <= size < sys.maxsize |
| 242 | block = BufferWrapper._heap.malloc(size) |
| 243 | self._state = (block, size) |
| 244 | Finalize(self, BufferWrapper._heap.free, args=(block,)) |
| 245 | |
| 246 | def get_address(self): |
| 247 | (arena, start, stop), size = self._state |
| 248 | address, length = _multiprocessing.address_of_buffer(arena.buffer) |
| 249 | assert size <= length |
| 250 | return address + start |
| 251 | |
| 252 | def get_size(self): |
| 253 | return self._state[1] |