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 | # |
| 6 | # Copyright (c) 2007-2008, R Oudkerk --- see COPYING.txt |
| 7 | # |
| 8 | |
| 9 | import sys |
| 10 | import ctypes |
| 11 | import weakref |
| 12 | import copyreg |
| 13 | |
| 14 | from multiprocessing import heap, RLock |
| 15 | from multiprocessing.forking import assert_spawning |
| 16 | |
| 17 | __all__ = ['RawValue', 'RawArray', 'Value', 'Array', 'copy', 'synchronized'] |
| 18 | |
| 19 | # |
| 20 | # |
| 21 | # |
| 22 | |
| 23 | typecode_to_type = { |
| 24 | 'c': ctypes.c_char, 'u': ctypes.c_wchar, |
| 25 | 'b': ctypes.c_byte, 'B': ctypes.c_ubyte, |
| 26 | 'h': ctypes.c_short, 'H': ctypes.c_ushort, |
| 27 | 'i': ctypes.c_int, 'I': ctypes.c_uint, |
| 28 | 'l': ctypes.c_long, 'L': ctypes.c_ulong, |
| 29 | 'f': ctypes.c_float, 'd': ctypes.c_double |
| 30 | } |
| 31 | |
| 32 | # |
| 33 | # |
| 34 | # |
| 35 | |
| 36 | def _new_value(type_): |
| 37 | size = ctypes.sizeof(type_) |
| 38 | wrapper = heap.BufferWrapper(size) |
| 39 | return rebuild_ctype(type_, wrapper, None) |
| 40 | |
| 41 | def RawValue(typecode_or_type, *args): |
| 42 | ''' |
| 43 | Returns a ctypes object allocated from shared memory |
| 44 | ''' |
| 45 | type_ = typecode_to_type.get(typecode_or_type, typecode_or_type) |
| 46 | obj = _new_value(type_) |
| 47 | ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj)) |
| 48 | obj.__init__(*args) |
| 49 | return obj |
| 50 | |
| 51 | def RawArray(typecode_or_type, size_or_initializer): |
| 52 | ''' |
| 53 | Returns a ctypes array allocated from shared memory |
| 54 | ''' |
| 55 | type_ = typecode_to_type.get(typecode_or_type, typecode_or_type) |
| 56 | if isinstance(size_or_initializer, int): |
| 57 | type_ = type_ * size_or_initializer |
| 58 | return _new_value(type_) |
| 59 | else: |
| 60 | type_ = type_ * len(size_or_initializer) |
| 61 | result = _new_value(type_) |
| 62 | result.__init__(*size_or_initializer) |
| 63 | return result |
| 64 | |
| 65 | def Value(typecode_or_type, *args, **kwds): |
| 66 | ''' |
| 67 | Return a synchronization wrapper for a Value |
| 68 | ''' |
| 69 | lock = kwds.pop('lock', None) |
| 70 | if kwds: |
| 71 | raise ValueError('unrecognized keyword argument(s): %s' % list(kwds.keys())) |
| 72 | obj = RawValue(typecode_or_type, *args) |
| 73 | if lock is None: |
| 74 | lock = RLock() |
| 75 | assert hasattr(lock, 'acquire') |
| 76 | return synchronized(obj, lock) |
| 77 | |
| 78 | def Array(typecode_or_type, size_or_initializer, **kwds): |
| 79 | ''' |
| 80 | Return a synchronization wrapper for a RawArray |
| 81 | ''' |
| 82 | lock = kwds.pop('lock', None) |
| 83 | if kwds: |
| 84 | raise ValueError('unrecognized keyword argument(s): %s' % list(kwds.keys())) |
| 85 | obj = RawArray(typecode_or_type, size_or_initializer) |
| 86 | if lock is None: |
| 87 | lock = RLock() |
| 88 | assert hasattr(lock, 'acquire') |
| 89 | return synchronized(obj, lock) |
| 90 | |
| 91 | def copy(obj): |
| 92 | new_obj = _new_value(type(obj)) |
| 93 | ctypes.pointer(new_obj)[0] = obj |
| 94 | return new_obj |
| 95 | |
| 96 | def synchronized(obj, lock=None): |
| 97 | assert not isinstance(obj, SynchronizedBase), 'object already synchronized' |
| 98 | |
| 99 | if isinstance(obj, ctypes._SimpleCData): |
| 100 | return Synchronized(obj, lock) |
| 101 | elif isinstance(obj, ctypes.Array): |
| 102 | if obj._type_ is ctypes.c_char: |
| 103 | return SynchronizedString(obj, lock) |
| 104 | return SynchronizedArray(obj, lock) |
| 105 | else: |
| 106 | cls = type(obj) |
| 107 | try: |
| 108 | scls = class_cache[cls] |
| 109 | except KeyError: |
| 110 | names = [field[0] for field in cls._fields_] |
| 111 | d = dict((name, make_property(name)) for name in names) |
| 112 | classname = 'Synchronized' + cls.__name__ |
| 113 | scls = class_cache[cls] = type(classname, (SynchronizedBase,), d) |
| 114 | return scls(obj, lock) |
| 115 | |
| 116 | # |
| 117 | # Functions for pickling/unpickling |
| 118 | # |
| 119 | |
| 120 | def reduce_ctype(obj): |
| 121 | assert_spawning(obj) |
| 122 | if isinstance(obj, ctypes.Array): |
| 123 | return rebuild_ctype, (obj._type_, obj._wrapper, obj._length_) |
| 124 | else: |
| 125 | return rebuild_ctype, (type(obj), obj._wrapper, None) |
| 126 | |
| 127 | def rebuild_ctype(type_, wrapper, length): |
| 128 | if length is not None: |
| 129 | type_ = type_ * length |
| 130 | if sys.platform == 'win32' and type_ not in copyreg.dispatch_table: |
| 131 | copyreg.pickle(type_, reduce_ctype) |
| 132 | obj = type_.from_address(wrapper.get_address()) |
| 133 | obj._wrapper = wrapper |
| 134 | return obj |
| 135 | |
| 136 | # |
| 137 | # Function to create properties |
| 138 | # |
| 139 | |
| 140 | def make_property(name): |
| 141 | try: |
| 142 | return prop_cache[name] |
| 143 | except KeyError: |
| 144 | d = {} |
| 145 | exec(template % ((name,)*7), d) |
| 146 | prop_cache[name] = d[name] |
| 147 | return d[name] |
| 148 | |
| 149 | template = ''' |
| 150 | def get%s(self): |
| 151 | self.acquire() |
| 152 | try: |
| 153 | return self._obj.%s |
| 154 | finally: |
| 155 | self.release() |
| 156 | def set%s(self, value): |
| 157 | self.acquire() |
| 158 | try: |
| 159 | self._obj.%s = value |
| 160 | finally: |
| 161 | self.release() |
| 162 | %s = property(get%s, set%s) |
| 163 | ''' |
| 164 | |
| 165 | prop_cache = {} |
| 166 | class_cache = weakref.WeakKeyDictionary() |
| 167 | |
| 168 | # |
| 169 | # Synchronized wrappers |
| 170 | # |
| 171 | |
| 172 | class SynchronizedBase(object): |
| 173 | |
| 174 | def __init__(self, obj, lock=None): |
| 175 | self._obj = obj |
| 176 | self._lock = lock or RLock() |
| 177 | self.acquire = self._lock.acquire |
| 178 | self.release = self._lock.release |
| 179 | |
| 180 | def __reduce__(self): |
| 181 | assert_spawning(self) |
| 182 | return synchronized, (self._obj, self._lock) |
| 183 | |
| 184 | def get_obj(self): |
| 185 | return self._obj |
| 186 | |
| 187 | def get_lock(self): |
| 188 | return self._lock |
| 189 | |
| 190 | def __repr__(self): |
| 191 | return '<%s wrapper for %s>' % (type(self).__name__, self._obj) |
| 192 | |
| 193 | |
| 194 | class Synchronized(SynchronizedBase): |
| 195 | value = make_property('value') |
| 196 | |
| 197 | |
| 198 | class SynchronizedArray(SynchronizedBase): |
| 199 | |
| 200 | def __len__(self): |
| 201 | return len(self._obj) |
| 202 | |
| 203 | def __getitem__(self, i): |
| 204 | self.acquire() |
| 205 | try: |
| 206 | return self._obj[i] |
| 207 | finally: |
| 208 | self.release() |
| 209 | |
| 210 | def __setitem__(self, i, value): |
| 211 | self.acquire() |
| 212 | try: |
| 213 | self._obj[i] = value |
| 214 | finally: |
| 215 | self.release() |
| 216 | |
| 217 | def __getslice__(self, start, stop): |
| 218 | self.acquire() |
| 219 | try: |
| 220 | return self._obj[start:stop] |
| 221 | finally: |
| 222 | self.release() |
| 223 | |
| 224 | def __setslice__(self, start, stop, values): |
| 225 | self.acquire() |
| 226 | try: |
| 227 | self._obj[start:stop] = values |
| 228 | finally: |
| 229 | self.release() |
| 230 | |
| 231 | |
| 232 | class SynchronizedString(SynchronizedArray): |
| 233 | value = make_property('value') |
| 234 | raw = make_property('raw') |