heap.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. #
  2. # Module which supports allocation of memory from an mmap
  3. #
  4. # multiprocessing/heap.py
  5. #
  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.
  33. #
  34. import bisect
  35. import mmap
  36. import tempfile
  37. import os
  38. import sys
  39. import threading
  40. import itertools
  41. import _multiprocessing
  42. from multiprocessing.util import Finalize, info
  43. from multiprocessing.forking import assert_spawning
  44. __all__ = ['BufferWrapper']
  45. #
  46. # Inheirtable class which wraps an mmap, and from which blocks can be allocated
  47. #
  48. if sys.platform == 'win32':
  49. from _multiprocessing import win32
  50. class Arena(object):
  51. _counter = itertools.count()
  52. def __init__(self, size):
  53. self.size = size
  54. self.name = 'pym-%d-%d' % (os.getpid(), Arena._counter.next())
  55. self.buffer = mmap.mmap(-1, self.size, tagname=self.name)
  56. assert win32.GetLastError() == 0, 'tagname already in use'
  57. self._state = (self.size, self.name)
  58. def __getstate__(self):
  59. assert_spawning(self)
  60. return self._state
  61. def __setstate__(self, state):
  62. self.size, self.name = self._state = state
  63. self.buffer = mmap.mmap(-1, self.size, tagname=self.name)
  64. assert win32.GetLastError() == win32.ERROR_ALREADY_EXISTS
  65. else:
  66. class Arena(object):
  67. def __init__(self, size):
  68. self.buffer = mmap.mmap(-1, size)
  69. self.size = size
  70. self.name = None
  71. #
  72. # Class allowing allocation of chunks of memory from arenas
  73. #
  74. class Heap(object):
  75. _alignment = 8
  76. def __init__(self, size=mmap.PAGESIZE):
  77. self._lastpid = os.getpid()
  78. self._lock = threading.Lock()
  79. self._size = size
  80. self._lengths = []
  81. self._len_to_seq = {}
  82. self._start_to_block = {}
  83. self._stop_to_block = {}
  84. self._allocated_blocks = set()
  85. self._arenas = []
  86. # list of pending blocks to free - see free() comment below
  87. self._pending_free_blocks = []
  88. @staticmethod
  89. def _roundup(n, alignment):
  90. # alignment must be a power of 2
  91. mask = alignment - 1
  92. return (n + mask) & ~mask
  93. def _malloc(self, size):
  94. # returns a large enough block -- it might be much larger
  95. i = bisect.bisect_left(self._lengths, size)
  96. if i == len(self._lengths):
  97. length = self._roundup(max(self._size, size), mmap.PAGESIZE)
  98. self._size *= 2
  99. info('allocating a new mmap of length %d', length)
  100. arena = Arena(length)
  101. self._arenas.append(arena)
  102. return (arena, 0, length)
  103. else:
  104. length = self._lengths[i]
  105. seq = self._len_to_seq[length]
  106. block = seq.pop()
  107. if not seq:
  108. del self._len_to_seq[length], self._lengths[i]
  109. (arena, start, stop) = block
  110. del self._start_to_block[(arena, start)]
  111. del self._stop_to_block[(arena, stop)]
  112. return block
  113. def _free(self, block):
  114. # free location and try to merge with neighbours
  115. (arena, start, stop) = block
  116. try:
  117. prev_block = self._stop_to_block[(arena, start)]
  118. except KeyError:
  119. pass
  120. else:
  121. start, _ = self._absorb(prev_block)
  122. try:
  123. next_block = self._start_to_block[(arena, stop)]
  124. except KeyError:
  125. pass
  126. else:
  127. _, stop = self._absorb(next_block)
  128. block = (arena, start, stop)
  129. length = stop - start
  130. try:
  131. self._len_to_seq[length].append(block)
  132. except KeyError:
  133. self._len_to_seq[length] = [block]
  134. bisect.insort(self._lengths, length)
  135. self._start_to_block[(arena, start)] = block
  136. self._stop_to_block[(arena, stop)] = block
  137. def _absorb(self, block):
  138. # deregister this block so it can be merged with a neighbour
  139. (arena, start, stop) = block
  140. del self._start_to_block[(arena, start)]
  141. del self._stop_to_block[(arena, stop)]
  142. length = stop - start
  143. seq = self._len_to_seq[length]
  144. seq.remove(block)
  145. if not seq:
  146. del self._len_to_seq[length]
  147. self._lengths.remove(length)
  148. return start, stop
  149. def _free_pending_blocks(self):
  150. # Free all the blocks in the pending list - called with the lock held.
  151. while True:
  152. try:
  153. block = self._pending_free_blocks.pop()
  154. except IndexError:
  155. break
  156. self._allocated_blocks.remove(block)
  157. self._free(block)
  158. def free(self, block):
  159. # free a block returned by malloc()
  160. # Since free() can be called asynchronously by the GC, it could happen
  161. # that it's called while self._lock is held: in that case,
  162. # self._lock.acquire() would deadlock (issue #12352). To avoid that, a
  163. # trylock is used instead, and if the lock can't be acquired
  164. # immediately, the block is added to a list of blocks to be freed
  165. # synchronously sometimes later from malloc() or free(), by calling
  166. # _free_pending_blocks() (appending and retrieving from a list is not
  167. # strictly thread-safe but under cPython it's atomic thanks to the GIL).
  168. assert os.getpid() == self._lastpid
  169. if not self._lock.acquire(False):
  170. # can't acquire the lock right now, add the block to the list of
  171. # pending blocks to free
  172. self._pending_free_blocks.append(block)
  173. else:
  174. # we hold the lock
  175. try:
  176. self._free_pending_blocks()
  177. self._allocated_blocks.remove(block)
  178. self._free(block)
  179. finally:
  180. self._lock.release()
  181. def malloc(self, size):
  182. # return a block of right size (possibly rounded up)
  183. assert 0 <= size < sys.maxint
  184. if os.getpid() != self._lastpid:
  185. self.__init__() # reinitialize after fork
  186. self._lock.acquire()
  187. self._free_pending_blocks()
  188. try:
  189. size = self._roundup(max(size,1), self._alignment)
  190. (arena, start, stop) = self._malloc(size)
  191. new_stop = start + size
  192. if new_stop < stop:
  193. self._free((arena, new_stop, stop))
  194. block = (arena, start, new_stop)
  195. self._allocated_blocks.add(block)
  196. return block
  197. finally:
  198. self._lock.release()
  199. #
  200. # Class representing a chunk of an mmap -- can be inherited
  201. #
  202. class BufferWrapper(object):
  203. _heap = Heap()
  204. def __init__(self, size):
  205. assert 0 <= size < sys.maxint
  206. block = BufferWrapper._heap.malloc(size)
  207. self._state = (block, size)
  208. Finalize(self, BufferWrapper._heap.free, args=(block,))
  209. def get_address(self):
  210. (arena, start, stop), size = self._state
  211. address, length = _multiprocessing.address_of_buffer(arena.buffer)
  212. assert size <= length
  213. return address + start
  214. def get_size(self):
  215. return self._state[1]