paulb@1 | 1 | #!/usr/bin/env python |
paulb@1 | 2 | |
paulb@1 | 3 | """ |
paulb@1 | 4 | A simple parallel processing API for Python, inspired somewhat by the thread |
paulb@1 | 5 | module, slightly less by pypar, and slightly less still by pypvm. |
paulb@1 | 6 | |
paulb@3 | 7 | Thread-style Processing |
paulb@3 | 8 | ----------------------- |
paulb@3 | 9 | |
paulb@1 | 10 | To create new processes to run a function or any callable object, specify the |
paulb@1 | 11 | "callable" and any arguments as follows: |
paulb@1 | 12 | |
paulb@1 | 13 | channel = start(fn, arg1, arg2, named1=value1, named2=value2) |
paulb@1 | 14 | |
paulb@1 | 15 | This returns a channel which can then be used to communicate with the created |
paulb@1 | 16 | process. Meanwhile, in the created process, the given callable will be invoked |
paulb@1 | 17 | with another channel as its first argument followed by the specified arguments: |
paulb@1 | 18 | |
paulb@1 | 19 | def fn(channel, arg1, arg2, named1, named2): |
paulb@3 | 20 | # Read from and write to the channel. |
paulb@1 | 21 | # Return value is ignored. |
paulb@1 | 22 | ... |
paulb@1 | 23 | |
paulb@3 | 24 | Fork-style Processing |
paulb@3 | 25 | --------------------- |
paulb@3 | 26 | |
paulb@1 | 27 | To create new processes in a similar way to that employed when using os.fork |
paulb@1 | 28 | (ie. the fork system call on various operating systems), use the following |
paulb@1 | 29 | method: |
paulb@1 | 30 | |
paulb@1 | 31 | channel = create() |
paulb@1 | 32 | if channel.pid == 0: |
paulb@1 | 33 | # This code is run by the created process. |
paulb@3 | 34 | # Read from and write to the channel to communicate with the |
paulb@1 | 35 | # creating/calling process. |
paulb@1 | 36 | # An explicit exit of the process may be desirable to prevent the process |
paulb@1 | 37 | # from running code which is intended for the creating/calling process. |
paulb@1 | 38 | ... |
paulb@1 | 39 | else: |
paulb@1 | 40 | # This code is run by the creating/calling process. |
paulb@3 | 41 | # Read from and write to the channel to communicate with the created |
paulb@1 | 42 | # process. |
paulb@1 | 43 | ... |
paulb@3 | 44 | |
paulb@3 | 45 | Message Exchanges |
paulb@3 | 46 | ----------------- |
paulb@3 | 47 | |
paulb@3 | 48 | When creating many processes, each providing results for the consumption of the |
paulb@3 | 49 | main process, the collection of those results in an efficient fashion can be |
paulb@3 | 50 | problematic: if some processes take longer than others, and if we decide to read |
paulb@3 | 51 | from those processes when they are not ready instead of other processes which |
paulb@3 | 52 | are ready, the whole activity will take much longer than necessary. |
paulb@3 | 53 | |
paulb@3 | 54 | One solution to the problem of knowing when to read from channels is to create |
paulb@3 | 55 | an Exchange object, initialising it with a list of channels through which data |
paulb@3 | 56 | is expected to arrive: |
paulb@3 | 57 | |
paulb@3 | 58 | exchange = Exchange(channels) |
paulb@3 | 59 | |
paulb@21 | 60 | To test whether an exchange is active - that is, whether it is actually |
paulb@21 | 61 | monitoring any channels - we can use the active method which returns all |
paulb@21 | 62 | channels being monitored by the exchange: |
paulb@21 | 63 | |
paulb@21 | 64 | channels = exchange.active() |
paulb@21 | 65 | |
paulb@3 | 66 | We may then check the exchange to see whether any data is ready to be received; |
paulb@3 | 67 | for example: |
paulb@3 | 68 | |
paulb@3 | 69 | for channel in exchange.ready(): |
paulb@3 | 70 | # Read from and write to the channel. |
paulb@3 | 71 | ... |
paulb@3 | 72 | |
paulb@3 | 73 | If we do not wish to wait indefinitely for a list of channels, we can set a |
paulb@3 | 74 | timeout value as an argument to the ready method (as a floating point number |
paulb@3 | 75 | specifying the timeout in seconds, where 0 means a non-blocking poll as stated |
paulb@3 | 76 | in the select module's select function documentation). |
paulb@7 | 77 | |
paulb@7 | 78 | Signals and Waiting |
paulb@7 | 79 | ------------------- |
paulb@7 | 80 | |
paulb@7 | 81 | When created/child processes terminate, one would typically want to be informed |
paulb@7 | 82 | of such conditions using a signal handler. Unfortunately, Python seems to have |
paulb@7 | 83 | issues with restartable reads from file descriptors when interrupted by signals: |
paulb@7 | 84 | |
paulb@7 | 85 | http://mail.python.org/pipermail/python-dev/2002-September/028572.html |
paulb@9 | 86 | http://twistedmatrix.com/bugs/issue733 |
paulb@11 | 87 | |
paulb@11 | 88 | Select and Poll |
paulb@11 | 89 | --------------- |
paulb@11 | 90 | |
paulb@11 | 91 | The exact combination of conditions indicating closed pipes remains relatively |
paulb@11 | 92 | obscure. Here is a message/thread describing them (in the context of another |
paulb@11 | 93 | topic): |
paulb@11 | 94 | |
paulb@11 | 95 | http://twistedmatrix.com/pipermail/twisted-python/2005-February/009666.html |
paulb@1 | 96 | """ |
paulb@1 | 97 | |
paulb@21 | 98 | __version__ = "0.1" |
paulb@21 | 99 | |
paulb@1 | 100 | import os |
paulb@1 | 101 | import sys |
paulb@5 | 102 | import select |
paulb@15 | 103 | import socket |
paulb@1 | 104 | |
paulb@1 | 105 | try: |
paulb@1 | 106 | import cPickle as pickle |
paulb@1 | 107 | except ImportError: |
paulb@1 | 108 | import pickle |
paulb@1 | 109 | |
paulb@1 | 110 | class Channel: |
paulb@1 | 111 | |
paulb@1 | 112 | "A communications channel." |
paulb@1 | 113 | |
paulb@1 | 114 | def __init__(self, pid, read_pipe, write_pipe): |
paulb@1 | 115 | |
paulb@1 | 116 | """ |
paulb@1 | 117 | Initialise the channel with a process identifier 'pid', a 'read_pipe' |
paulb@1 | 118 | from which messages will be received, and a 'write_pipe' into which |
paulb@1 | 119 | messages will be sent. |
paulb@1 | 120 | """ |
paulb@1 | 121 | |
paulb@1 | 122 | self.pid = pid |
paulb@1 | 123 | self.read_pipe = read_pipe |
paulb@1 | 124 | self.write_pipe = write_pipe |
paulb@7 | 125 | self.closed = 0 |
paulb@1 | 126 | |
paulb@5 | 127 | def __del__(self): |
paulb@5 | 128 | |
paulb@14 | 129 | # Since signals don't work well with I/O, we close pipes and wait for |
paulb@14 | 130 | # created processes upon finalisation. |
paulb@5 | 131 | |
paulb@7 | 132 | if not self.closed: |
paulb@7 | 133 | self.close() |
paulb@7 | 134 | |
paulb@7 | 135 | def close(self): |
paulb@7 | 136 | |
paulb@7 | 137 | "Explicitly close the channel." |
paulb@7 | 138 | |
paulb@7 | 139 | self.closed = 1 |
paulb@7 | 140 | self.read_pipe.close() |
paulb@7 | 141 | self.write_pipe.close() |
paulb@11 | 142 | self.wait(os.WNOHANG) |
paulb@9 | 143 | |
paulb@11 | 144 | def wait(self, options=0): |
paulb@9 | 145 | |
paulb@9 | 146 | "Wait for the created process, if any, to exit." |
paulb@9 | 147 | |
paulb@5 | 148 | if self.pid != 0: |
paulb@5 | 149 | try: |
paulb@11 | 150 | os.waitpid(self.pid, options) |
paulb@5 | 151 | except OSError: |
paulb@5 | 152 | pass |
paulb@5 | 153 | |
paulb@1 | 154 | def send(self, obj): |
paulb@1 | 155 | |
paulb@1 | 156 | "Send the given object 'obj' through the channel." |
paulb@1 | 157 | |
paulb@1 | 158 | pickle.dump(obj, self.write_pipe) |
paulb@1 | 159 | self.write_pipe.flush() |
paulb@1 | 160 | |
paulb@1 | 161 | def receive(self): |
paulb@1 | 162 | |
paulb@1 | 163 | "Receive an object through the channel, returning the object." |
paulb@1 | 164 | |
paulb@1 | 165 | obj = pickle.load(self.read_pipe) |
paulb@1 | 166 | if isinstance(obj, Exception): |
paulb@1 | 167 | raise obj |
paulb@1 | 168 | else: |
paulb@1 | 169 | return obj |
paulb@1 | 170 | |
paulb@3 | 171 | class Exchange: |
paulb@3 | 172 | |
paulb@3 | 173 | """ |
paulb@3 | 174 | A communications exchange that can be used to detect channels which are |
paulb@3 | 175 | ready to communicate. |
paulb@3 | 176 | """ |
paulb@3 | 177 | |
paulb@3 | 178 | def __init__(self, channels): |
paulb@3 | 179 | |
paulb@3 | 180 | "Initialise the exchange with the given 'channels'." |
paulb@3 | 181 | |
paulb@3 | 182 | self.readables = {} |
paulb@9 | 183 | self.poller = select.poll() |
paulb@3 | 184 | for channel in channels: |
paulb@9 | 185 | self.readables[channel.read_pipe.fileno()] = channel |
paulb@15 | 186 | self.poller.register(channel.read_pipe.fileno(), select.POLLIN | select.POLLHUP | select.POLLNVAL | select.POLLERR) |
paulb@3 | 187 | |
paulb@7 | 188 | def active(self): |
paulb@7 | 189 | |
paulb@21 | 190 | "Return a list of active channels." |
paulb@7 | 191 | |
paulb@21 | 192 | return self.readables.values() |
paulb@7 | 193 | |
paulb@3 | 194 | def ready(self, timeout=None): |
paulb@3 | 195 | |
paulb@3 | 196 | """ |
paulb@3 | 197 | Wait for a period of time specified by the optional 'timeout' (or until |
paulb@3 | 198 | communication is possible) and return a list of channels which are ready |
paulb@3 | 199 | to be read from. |
paulb@3 | 200 | """ |
paulb@3 | 201 | |
paulb@9 | 202 | fds = self.poller.poll(timeout) |
paulb@9 | 203 | readables = [] |
paulb@9 | 204 | for fd, status in fds: |
paulb@9 | 205 | channel = self.readables[fd] |
paulb@9 | 206 | |
paulb@9 | 207 | # Remove ended/error channels. |
paulb@9 | 208 | |
paulb@15 | 209 | if status & (select.POLLHUP | select.POLLNVAL | select.POLLERR): |
paulb@9 | 210 | self.remove(channel) |
paulb@9 | 211 | |
paulb@17 | 212 | # Record readable channels. |
paulb@17 | 213 | |
paulb@17 | 214 | elif status & select.POLLIN: |
paulb@17 | 215 | readables.append(channel) |
paulb@17 | 216 | |
paulb@9 | 217 | return readables |
paulb@3 | 218 | |
paulb@7 | 219 | def remove(self, channel): |
paulb@7 | 220 | |
paulb@7 | 221 | """ |
paulb@7 | 222 | Remove the given 'channel' from the exchange. |
paulb@7 | 223 | """ |
paulb@7 | 224 | |
paulb@9 | 225 | del self.readables[channel.read_pipe.fileno()] |
paulb@9 | 226 | self.poller.unregister(channel.read_pipe.fileno()) |
paulb@7 | 227 | |
paulb@1 | 228 | def create(): |
paulb@1 | 229 | |
paulb@1 | 230 | """ |
paulb@1 | 231 | Create a new process, returning a communications channel to both the |
paulb@1 | 232 | creating process and the created process. |
paulb@1 | 233 | """ |
paulb@1 | 234 | |
paulb@16 | 235 | parent, child = socket.socketpair() |
paulb@16 | 236 | for s in [parent, child]: |
paulb@15 | 237 | s.setblocking(1) |
paulb@1 | 238 | |
paulb@1 | 239 | pid = os.fork() |
paulb@1 | 240 | if pid == 0: |
paulb@16 | 241 | parent.close() |
paulb@16 | 242 | return Channel(pid, child.makefile("r"), child.makefile("w")) |
paulb@1 | 243 | else: |
paulb@16 | 244 | child.close() |
paulb@16 | 245 | return Channel(pid, parent.makefile("r"), parent.makefile("w")) |
paulb@1 | 246 | |
paulb@1 | 247 | def start(callable, *args, **kwargs): |
paulb@1 | 248 | |
paulb@1 | 249 | """ |
paulb@1 | 250 | Create a new process which shall start running in the given 'callable'. |
paulb@1 | 251 | Return a communications channel to the creating process, and supply such a |
paulb@1 | 252 | channel to the created process as the 'channel' parameter in the given |
paulb@1 | 253 | 'callable'. Additional arguments to the 'callable' can be given as |
paulb@1 | 254 | additional arguments to this function. |
paulb@1 | 255 | """ |
paulb@1 | 256 | |
paulb@1 | 257 | channel = create() |
paulb@1 | 258 | if channel.pid == 0: |
paulb@1 | 259 | try: |
paulb@1 | 260 | try: |
paulb@1 | 261 | callable(channel, *args, **kwargs) |
paulb@1 | 262 | except: |
paulb@1 | 263 | exc_type, exc_value, exc_traceback = sys.exc_info() |
paulb@1 | 264 | channel.send(exc_value) |
paulb@1 | 265 | finally: |
paulb@9 | 266 | channel.close() |
paulb@11 | 267 | sys.exit(0) |
paulb@1 | 268 | else: |
paulb@1 | 269 | return channel |
paulb@1 | 270 | |
paulb@19 | 271 | def waitall(): |
paulb@19 | 272 | |
paulb@19 | 273 | "Wait for all created processes to terminate." |
paulb@19 | 274 | |
paulb@19 | 275 | try: |
paulb@19 | 276 | while 1: |
paulb@19 | 277 | os.wait() |
paulb@19 | 278 | except OSError: |
paulb@19 | 279 | pass |
paulb@19 | 280 | |
paulb@1 | 281 | # vim: tabstop=4 expandtab shiftwidth=4 |