blob: 1e694da49d9e9a98b77c3f05b8759cdf2f52caf5 [file] [log] [blame]
Benjamin Petersone711caf2008-06-11 16:44:04 +00001#
2# Module which supports allocation of ctypes objects from shared memory
3#
4# multiprocessing/sharedctypes.py
5#
R. David Murrayd3820662010-12-14 01:41:07 +00006# 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 Petersone711caf2008-06-11 16:44:04 +000033#
34
35import sys
36import ctypes
37import weakref
Benjamin Petersone711caf2008-06-11 16:44:04 +000038
39from multiprocessing import heap, RLock
Amaury Forgeot d'Arc949d47d2008-08-19 21:30:55 +000040from multiprocessing.forking import assert_spawning, ForkingPickler
Benjamin Petersone711caf2008-06-11 16:44:04 +000041
42__all__ = ['RawValue', 'RawArray', 'Value', 'Array', 'copy', 'synchronized']
43
44#
45#
46#
47
48typecode_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
61def _new_value(type_):
62 size = ctypes.sizeof(type_)
63 wrapper = heap.BufferWrapper(size)
64 return rebuild_ctype(type_, wrapper, None)
65
66def 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
76def 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 Dickinson89461ef2011-03-26 10:19:03 +000083 obj = _new_value(type_)
84 ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj))
85 return obj
Benjamin Petersone711caf2008-06-11 16:44:04 +000086 else:
87 type_ = type_ * len(size_or_initializer)
88 result = _new_value(type_)
89 result.__init__(*size_or_initializer)
90 return result
91
Benjamin Petersond5cd65b2008-06-27 22:16:47 +000092def Value(typecode_or_type, *args, lock=None):
Benjamin Petersone711caf2008-06-11 16:44:04 +000093 '''
94 Return a synchronization wrapper for a Value
95 '''
Benjamin Petersone711caf2008-06-11 16:44:04 +000096 obj = RawValue(typecode_or_type, *args)
Jesse Nollerb0516a62009-01-18 03:11:38 +000097 if lock is False:
98 return obj
99 if lock in (True, None):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000100 lock = RLock()
Jesse Nollerb0516a62009-01-18 03:11:38 +0000101 if not hasattr(lock, 'acquire'):
102 raise AttributeError("'%r' has no method 'acquire'" % lock)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000103 return synchronized(obj, lock)
104
105def 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 Nollerb0516a62009-01-18 03:11:38 +0000113 if lock is False:
114 return obj
115 if lock in (True, None):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000116 lock = RLock()
Jesse Nollerb0516a62009-01-18 03:11:38 +0000117 if not hasattr(lock, 'acquire'):
118 raise AttributeError("'%r' has no method 'acquire'" % lock)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000119 return synchronized(obj, lock)
120
121def copy(obj):
122 new_obj = _new_value(type(obj))
123 ctypes.pointer(new_obj)[0] = obj
124 return new_obj
125
126def 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
150def 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
157def rebuild_ctype(type_, wrapper, length):
158 if length is not None:
159 type_ = type_ * length
Amaury Forgeot d'Arc949d47d2008-08-19 21:30:55 +0000160 ForkingPickler.register(type_, reduce_ctype)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000161 obj = type_.from_address(wrapper.get_address())
162 obj._wrapper = wrapper
163 return obj
164
165#
166# Function to create properties
167#
168
169def 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
178template = '''
179def get%s(self):
180 self.acquire()
181 try:
182 return self._obj.%s
183 finally:
184 self.release()
185def 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
194prop_cache = {}
195class_cache = weakref.WeakKeyDictionary()
196
197#
198# Synchronized wrappers
199#
200
201class 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
223class Synchronized(SynchronizedBase):
224 value = make_property('value')
225
226
227class 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
261class SynchronizedString(SynchronizedArray):
262 value = make_property('value')
263 raw = make_property('raw')