Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1 | # |
| 2 | # Module which supports allocation of ctypes objects from shared memory |
| 3 | # |
| 4 | # multiprocessing/sharedctypes.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 sys |
| 36 | import ctypes |
| 37 | import weakref |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 38 | |
| 39 | from multiprocessing import heap, RLock |
Amaury Forgeot d'Arc | 949d47d | 2008-08-19 21:30:55 +0000 | [diff] [blame] | 40 | from multiprocessing.forking import assert_spawning, ForkingPickler |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 41 | |
| 42 | __all__ = ['RawValue', 'RawArray', 'Value', 'Array', 'copy', 'synchronized'] |
| 43 | |
| 44 | # |
| 45 | # |
| 46 | # |
| 47 | |
| 48 | typecode_to_type = { |
| 49 | 'c': ctypes.c_char, 'u': ctypes.c_wchar, |
| 50 | 'b': ctypes.c_byte, 'B': ctypes.c_ubyte, |
| 51 | 'h': ctypes.c_short, 'H': ctypes.c_ushort, |
| 52 | 'i': ctypes.c_int, 'I': ctypes.c_uint, |
| 53 | 'l': ctypes.c_long, 'L': ctypes.c_ulong, |
| 54 | 'f': ctypes.c_float, 'd': ctypes.c_double |
| 55 | } |
| 56 | |
| 57 | # |
| 58 | # |
| 59 | # |
| 60 | |
| 61 | def _new_value(type_): |
| 62 | size = ctypes.sizeof(type_) |
| 63 | wrapper = heap.BufferWrapper(size) |
| 64 | return rebuild_ctype(type_, wrapper, None) |
| 65 | |
| 66 | def RawValue(typecode_or_type, *args): |
| 67 | ''' |
| 68 | Returns a ctypes object allocated from shared memory |
| 69 | ''' |
| 70 | type_ = typecode_to_type.get(typecode_or_type, typecode_or_type) |
| 71 | obj = _new_value(type_) |
| 72 | ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj)) |
| 73 | obj.__init__(*args) |
| 74 | return obj |
| 75 | |
| 76 | def RawArray(typecode_or_type, size_or_initializer): |
| 77 | ''' |
| 78 | Returns a ctypes array allocated from shared memory |
| 79 | ''' |
| 80 | type_ = typecode_to_type.get(typecode_or_type, typecode_or_type) |
| 81 | if isinstance(size_or_initializer, int): |
| 82 | type_ = type_ * size_or_initializer |
Mark Dickinson | 89461ef | 2011-03-26 10:19:03 +0000 | [diff] [blame] | 83 | obj = _new_value(type_) |
| 84 | ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj)) |
| 85 | return obj |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 86 | else: |
| 87 | type_ = type_ * len(size_or_initializer) |
| 88 | result = _new_value(type_) |
| 89 | result.__init__(*size_or_initializer) |
| 90 | return result |
| 91 | |
Benjamin Peterson | d5cd65b | 2008-06-27 22:16:47 +0000 | [diff] [blame] | 92 | def Value(typecode_or_type, *args, lock=None): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 93 | ''' |
| 94 | Return a synchronization wrapper for a Value |
| 95 | ''' |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 96 | obj = RawValue(typecode_or_type, *args) |
Jesse Noller | b0516a6 | 2009-01-18 03:11:38 +0000 | [diff] [blame] | 97 | if lock is False: |
| 98 | return obj |
| 99 | if lock in (True, None): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 100 | lock = RLock() |
Jesse Noller | b0516a6 | 2009-01-18 03:11:38 +0000 | [diff] [blame] | 101 | if not hasattr(lock, 'acquire'): |
| 102 | raise AttributeError("'%r' has no method 'acquire'" % lock) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 103 | return synchronized(obj, lock) |
| 104 | |
| 105 | def Array(typecode_or_type, size_or_initializer, **kwds): |
| 106 | ''' |
| 107 | Return a synchronization wrapper for a RawArray |
| 108 | ''' |
| 109 | lock = kwds.pop('lock', None) |
| 110 | if kwds: |
| 111 | raise ValueError('unrecognized keyword argument(s): %s' % list(kwds.keys())) |
| 112 | obj = RawArray(typecode_or_type, size_or_initializer) |
Jesse Noller | b0516a6 | 2009-01-18 03:11:38 +0000 | [diff] [blame] | 113 | if lock is False: |
| 114 | return obj |
| 115 | if lock in (True, None): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 116 | lock = RLock() |
Jesse Noller | b0516a6 | 2009-01-18 03:11:38 +0000 | [diff] [blame] | 117 | if not hasattr(lock, 'acquire'): |
| 118 | raise AttributeError("'%r' has no method 'acquire'" % lock) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 119 | return synchronized(obj, lock) |
| 120 | |
| 121 | def copy(obj): |
| 122 | new_obj = _new_value(type(obj)) |
| 123 | ctypes.pointer(new_obj)[0] = obj |
| 124 | return new_obj |
| 125 | |
| 126 | def synchronized(obj, lock=None): |
| 127 | assert not isinstance(obj, SynchronizedBase), 'object already synchronized' |
| 128 | |
| 129 | if isinstance(obj, ctypes._SimpleCData): |
| 130 | return Synchronized(obj, lock) |
| 131 | elif isinstance(obj, ctypes.Array): |
| 132 | if obj._type_ is ctypes.c_char: |
| 133 | return SynchronizedString(obj, lock) |
| 134 | return SynchronizedArray(obj, lock) |
| 135 | else: |
| 136 | cls = type(obj) |
| 137 | try: |
| 138 | scls = class_cache[cls] |
| 139 | except KeyError: |
| 140 | names = [field[0] for field in cls._fields_] |
| 141 | d = dict((name, make_property(name)) for name in names) |
| 142 | classname = 'Synchronized' + cls.__name__ |
| 143 | scls = class_cache[cls] = type(classname, (SynchronizedBase,), d) |
| 144 | return scls(obj, lock) |
| 145 | |
| 146 | # |
| 147 | # Functions for pickling/unpickling |
| 148 | # |
| 149 | |
| 150 | def reduce_ctype(obj): |
| 151 | assert_spawning(obj) |
| 152 | if isinstance(obj, ctypes.Array): |
| 153 | return rebuild_ctype, (obj._type_, obj._wrapper, obj._length_) |
| 154 | else: |
| 155 | return rebuild_ctype, (type(obj), obj._wrapper, None) |
| 156 | |
| 157 | def rebuild_ctype(type_, wrapper, length): |
| 158 | if length is not None: |
| 159 | type_ = type_ * length |
Amaury Forgeot d'Arc | 949d47d | 2008-08-19 21:30:55 +0000 | [diff] [blame] | 160 | ForkingPickler.register(type_, reduce_ctype) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 161 | obj = type_.from_address(wrapper.get_address()) |
| 162 | obj._wrapper = wrapper |
| 163 | return obj |
| 164 | |
| 165 | # |
| 166 | # Function to create properties |
| 167 | # |
| 168 | |
| 169 | def make_property(name): |
| 170 | try: |
| 171 | return prop_cache[name] |
| 172 | except KeyError: |
| 173 | d = {} |
| 174 | exec(template % ((name,)*7), d) |
| 175 | prop_cache[name] = d[name] |
| 176 | return d[name] |
| 177 | |
| 178 | template = ''' |
| 179 | def get%s(self): |
| 180 | self.acquire() |
| 181 | try: |
| 182 | return self._obj.%s |
| 183 | finally: |
| 184 | self.release() |
| 185 | def set%s(self, value): |
| 186 | self.acquire() |
| 187 | try: |
| 188 | self._obj.%s = value |
| 189 | finally: |
| 190 | self.release() |
| 191 | %s = property(get%s, set%s) |
| 192 | ''' |
| 193 | |
| 194 | prop_cache = {} |
| 195 | class_cache = weakref.WeakKeyDictionary() |
| 196 | |
| 197 | # |
| 198 | # Synchronized wrappers |
| 199 | # |
| 200 | |
| 201 | class SynchronizedBase(object): |
| 202 | |
| 203 | def __init__(self, obj, lock=None): |
| 204 | self._obj = obj |
| 205 | self._lock = lock or RLock() |
| 206 | self.acquire = self._lock.acquire |
| 207 | self.release = self._lock.release |
| 208 | |
| 209 | def __reduce__(self): |
| 210 | assert_spawning(self) |
| 211 | return synchronized, (self._obj, self._lock) |
| 212 | |
| 213 | def get_obj(self): |
| 214 | return self._obj |
| 215 | |
| 216 | def get_lock(self): |
| 217 | return self._lock |
| 218 | |
| 219 | def __repr__(self): |
| 220 | return '<%s wrapper for %s>' % (type(self).__name__, self._obj) |
| 221 | |
| 222 | |
| 223 | class Synchronized(SynchronizedBase): |
| 224 | value = make_property('value') |
| 225 | |
| 226 | |
| 227 | class SynchronizedArray(SynchronizedBase): |
| 228 | |
| 229 | def __len__(self): |
| 230 | return len(self._obj) |
| 231 | |
| 232 | def __getitem__(self, i): |
| 233 | self.acquire() |
| 234 | try: |
| 235 | return self._obj[i] |
| 236 | finally: |
| 237 | self.release() |
| 238 | |
| 239 | def __setitem__(self, i, value): |
| 240 | self.acquire() |
| 241 | try: |
| 242 | self._obj[i] = value |
| 243 | finally: |
| 244 | self.release() |
| 245 | |
| 246 | def __getslice__(self, start, stop): |
| 247 | self.acquire() |
| 248 | try: |
| 249 | return self._obj[start:stop] |
| 250 | finally: |
| 251 | self.release() |
| 252 | |
| 253 | def __setslice__(self, start, stop, values): |
| 254 | self.acquire() |
| 255 | try: |
| 256 | self._obj[start:stop] = values |
| 257 | finally: |
| 258 | self.release() |
| 259 | |
| 260 | |
| 261 | class SynchronizedString(SynchronizedArray): |
| 262 | value = make_property('value') |
| 263 | raw = make_property('raw') |