paulb@40 | 1 | #!/usr/bin/env python |
paulb@40 | 2 | |
paulb@40 | 3 | """ |
paulb@40 | 4 | A simple parallel processing API for Python, inspired somewhat by the thread |
paulb@40 | 5 | module, slightly less by pypar, and slightly less still by pypvm. |
paulb@40 | 6 | |
paulb@67 | 7 | Copyright (C) 2005, 2006, 2007 Paul Boddie <paul@boddie.org.uk> |
paulb@41 | 8 | |
paulb@79 | 9 | This program is free software; you can redistribute it and/or modify it under |
paulb@79 | 10 | the terms of the GNU Lesser General Public License as published by the Free |
paulb@79 | 11 | Software Foundation; either version 3 of the License, or (at your option) any |
paulb@79 | 12 | later version. |
paulb@41 | 13 | |
paulb@79 | 14 | This program is distributed in the hope that it will be useful, but WITHOUT |
paulb@79 | 15 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
paulb@79 | 16 | FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more |
paulb@79 | 17 | details. |
paulb@41 | 18 | |
paulb@79 | 19 | You should have received a copy of the GNU Lesser General Public License along |
paulb@79 | 20 | with this program. If not, see <http://www.gnu.org/licenses/>. |
paulb@41 | 21 | |
paulb@41 | 22 | -------- |
paulb@41 | 23 | |
paulb@67 | 24 | The recommended styles of programming using pprocess involve the "Thread-style |
paulb@84 | 25 | Processing", "Convenient Message Exchanges", "Managed Callables" and "Map-style |
paulb@84 | 26 | Processing" sections below, although developers may wish to read the "Message |
paulb@84 | 27 | Exchanges" section for more details of the API concerned, and the "Fork-style |
paulb@84 | 28 | Processing" section may be of interest to those with experience of large scale |
paulb@84 | 29 | parallel processing systems. |
paulb@67 | 30 | |
paulb@40 | 31 | Thread-style Processing |
paulb@40 | 32 | ----------------------- |
paulb@40 | 33 | |
paulb@40 | 34 | To create new processes to run a function or any callable object, specify the |
paulb@40 | 35 | "callable" and any arguments as follows: |
paulb@40 | 36 | |
paulb@79 | 37 | channel = pprocess.start(fn, arg1, arg2, named1=value1, named2=value2) |
paulb@40 | 38 | |
paulb@40 | 39 | This returns a channel which can then be used to communicate with the created |
paulb@40 | 40 | process. Meanwhile, in the created process, the given callable will be invoked |
paulb@40 | 41 | with another channel as its first argument followed by the specified arguments: |
paulb@40 | 42 | |
paulb@40 | 43 | def fn(channel, arg1, arg2, named1, named2): |
paulb@40 | 44 | # Read from and write to the channel. |
paulb@40 | 45 | # Return value is ignored. |
paulb@40 | 46 | ... |
paulb@40 | 47 | |
paulb@40 | 48 | Fork-style Processing |
paulb@40 | 49 | --------------------- |
paulb@40 | 50 | |
paulb@40 | 51 | To create new processes in a similar way to that employed when using os.fork |
paulb@40 | 52 | (ie. the fork system call on various operating systems), use the following |
paulb@40 | 53 | method: |
paulb@40 | 54 | |
paulb@97 | 55 | channel = pprocess.create() |
paulb@40 | 56 | if channel.pid == 0: |
paulb@40 | 57 | # This code is run by the created process. |
paulb@40 | 58 | # Read from and write to the channel to communicate with the |
paulb@40 | 59 | # creating/calling process. |
paulb@40 | 60 | # An explicit exit of the process may be desirable to prevent the process |
paulb@40 | 61 | # from running code which is intended for the creating/calling process. |
paulb@40 | 62 | ... |
paulb@97 | 63 | pprocess.exit(channel) |
paulb@40 | 64 | else: |
paulb@40 | 65 | # This code is run by the creating/calling process. |
paulb@40 | 66 | # Read from and write to the channel to communicate with the created |
paulb@40 | 67 | # process. |
paulb@40 | 68 | ... |
paulb@40 | 69 | |
paulb@40 | 70 | Message Exchanges |
paulb@40 | 71 | ----------------- |
paulb@40 | 72 | |
paulb@40 | 73 | When creating many processes, each providing results for the consumption of the |
paulb@40 | 74 | main process, the collection of those results in an efficient fashion can be |
paulb@40 | 75 | problematic: if some processes take longer than others, and if we decide to read |
paulb@40 | 76 | from those processes when they are not ready instead of other processes which |
paulb@40 | 77 | are ready, the whole activity will take much longer than necessary. |
paulb@40 | 78 | |
paulb@40 | 79 | One solution to the problem of knowing when to read from channels is to create |
paulb@40 | 80 | an Exchange object, optionally initialising it with a list of channels through |
paulb@40 | 81 | which data is expected to arrive: |
paulb@40 | 82 | |
paulb@79 | 83 | exchange = pprocess.Exchange() # populate the exchange later |
paulb@79 | 84 | exchange = pprocess.Exchange(channels) # populate the exchange with channels |
paulb@40 | 85 | |
paulb@40 | 86 | We can add channels to the exchange using the add method: |
paulb@40 | 87 | |
paulb@40 | 88 | exchange.add(channel) |
paulb@40 | 89 | |
paulb@40 | 90 | To test whether an exchange is active - that is, whether it is actually |
paulb@40 | 91 | monitoring any channels - we can use the active method which returns all |
paulb@40 | 92 | channels being monitored by the exchange: |
paulb@40 | 93 | |
paulb@40 | 94 | channels = exchange.active() |
paulb@40 | 95 | |
paulb@40 | 96 | We may then check the exchange to see whether any data is ready to be received; |
paulb@40 | 97 | for example: |
paulb@40 | 98 | |
paulb@40 | 99 | for channel in exchange.ready(): |
paulb@40 | 100 | # Read from and write to the channel. |
paulb@40 | 101 | ... |
paulb@40 | 102 | |
paulb@40 | 103 | If we do not wish to wait indefinitely for a list of channels, we can set a |
paulb@40 | 104 | timeout value as an argument to the ready method (as a floating point number |
paulb@40 | 105 | specifying the timeout in seconds, where 0 means a non-blocking poll as stated |
paulb@40 | 106 | in the select module's select function documentation). |
paulb@40 | 107 | |
paulb@67 | 108 | Convenient Message Exchanges |
paulb@67 | 109 | ---------------------------- |
paulb@67 | 110 | |
paulb@67 | 111 | A convenient form of message exchanges can be adopted by defining a subclass of |
paulb@67 | 112 | the Exchange class and defining a particular method: |
paulb@67 | 113 | |
paulb@79 | 114 | class MyExchange(pprocess.Exchange): |
paulb@67 | 115 | def store_data(self, channel): |
paulb@67 | 116 | data = channel.receive() |
paulb@67 | 117 | # Do something with data here. |
paulb@67 | 118 | |
paulb@67 | 119 | The exact operations performed on the received data might be as simple as |
paulb@67 | 120 | storing it on an instance attribute. To make use of the exchange, we would |
paulb@67 | 121 | instantiate it as usual: |
paulb@67 | 122 | |
paulb@67 | 123 | exchange = MyExchange() # populate the exchange later |
paulb@67 | 124 | exchange = MyExchange(limit=10) # set a limit for later population |
paulb@67 | 125 | |
paulb@67 | 126 | The exchange can now be used in a simpler fashion than that shown above. We can |
paulb@67 | 127 | add channels as before using the add method, or we can choose to only add |
paulb@67 | 128 | channels if the specified limit of channels is not exceeded: |
paulb@67 | 129 | |
paulb@67 | 130 | exchange.add(channel) # add a channel as normal |
paulb@67 | 131 | exchange.add_wait(channel) # add a channel, waiting if the limit would be |
paulb@67 | 132 | # exceeded |
paulb@67 | 133 | |
paulb@97 | 134 | Or we can request that the exchange create a channel on our behalf: |
paulb@97 | 135 | |
paulb@97 | 136 | channel = exchange.create() |
paulb@97 | 137 | |
paulb@79 | 138 | We can even start processes and monitor channels without ever handling the |
paulb@79 | 139 | channel ourselves: |
paulb@79 | 140 | |
paulb@79 | 141 | exchange.start(fn, arg1, arg2, named1=value1, named2=value2) |
paulb@79 | 142 | |
paulb@79 | 143 | We can explicitly wait for "free space" for channels by calling the wait method, |
paulb@79 | 144 | although the start and add_wait methods make this less interesting: |
paulb@67 | 145 | |
paulb@67 | 146 | exchange.wait() |
paulb@67 | 147 | |
paulb@67 | 148 | Finally, when finishing the computation, we can choose to merely call the finish |
paulb@67 | 149 | method and have the remaining data processed automatically: |
paulb@67 | 150 | |
paulb@67 | 151 | exchange.finish() |
paulb@67 | 152 | |
paulb@67 | 153 | Clearly, this approach is less flexible but more convenient than the raw message |
paulb@67 | 154 | exchange API as described above. However, it permits much simpler and clearer |
paulb@67 | 155 | code. |
paulb@67 | 156 | |
paulb@97 | 157 | Exchanges as Queues |
paulb@97 | 158 | ------------------- |
paulb@97 | 159 | |
paulb@97 | 160 | Instead of having to subclass the pprocess.Exchange class and to define the |
paulb@97 | 161 | store_data method, it might be more desirable to let the exchange manage the |
paulb@97 | 162 | communications between created and creating processes and to let the creating |
paulb@97 | 163 | process just consume received data as it arrives, without particular regard for |
paulb@97 | 164 | the order of the received data - perhaps the creating process has its own way of |
paulb@97 | 165 | managing such issues. |
paulb@97 | 166 | |
paulb@97 | 167 | For such situations, the Queue class may be instantiated and channels added to |
paulb@97 | 168 | the queue using the various methods provided: |
paulb@97 | 169 | |
paulb@97 | 170 | queue = pprocess.Queue(limit=10) |
paulb@97 | 171 | channel = queue.create() |
paulb@97 | 172 | if channel: |
paulb@97 | 173 | # Do some computation. |
paulb@97 | 174 | pprocess.exit(channel) |
paulb@97 | 175 | |
paulb@97 | 176 | The results can then be consumed by treating the queue like an iterator: |
paulb@97 | 177 | |
paulb@97 | 178 | for result in queue: |
paulb@97 | 179 | # Capture each result. |
paulb@97 | 180 | |
paulb@97 | 181 | This approach does not, of course, require the direct handling of channels. One |
paulb@97 | 182 | could instead use the start method on the queue to create processes and to |
paulb@97 | 183 | initiate computations (since a queue is merely an enhanced exchange with a |
paulb@97 | 184 | specific implementation of the store_data method). |
paulb@97 | 185 | |
paulb@84 | 186 | Managed Callables |
paulb@84 | 187 | ----------------- |
paulb@84 | 188 | |
paulb@84 | 189 | A further simplification of the above convenient use of message exchanges |
paulb@84 | 190 | involves the creation of callables (eg. functions) which are automatically |
paulb@88 | 191 | monitored by an exchange. We create such a callable by calling the manage method |
paulb@84 | 192 | on an exchange: |
paulb@84 | 193 | |
paulb@88 | 194 | myfn = exchange.manage(fn) |
paulb@84 | 195 | |
paulb@84 | 196 | This callable can then be invoked instead of using the exchange's start method: |
paulb@84 | 197 | |
paulb@84 | 198 | myfn(arg1, arg2, named1=value1, named2=value2) |
paulb@84 | 199 | |
paulb@84 | 200 | The exchange's finish method can be used as usual to process incoming data. |
paulb@84 | 201 | |
paulb@92 | 202 | Making Existing Functions Parallel |
paulb@92 | 203 | ---------------------------------- |
paulb@92 | 204 | |
paulb@92 | 205 | In making a program parallel, existing functions which only return results can |
paulb@92 | 206 | be manually modified to accept and use channels to communicate results back to |
paulb@92 | 207 | the main process. However, a simple alternative is to use the MakeParallel class |
paulb@92 | 208 | to provide a wrapper around unmodified functions which will return the results |
paulb@92 | 209 | from those functions in the channels provided. For example: |
paulb@92 | 210 | |
paulb@92 | 211 | fn = pprocess.MakeParallel(originalfn) |
paulb@92 | 212 | |
paulb@84 | 213 | Map-style Processing |
paulb@84 | 214 | -------------------- |
paulb@84 | 215 | |
paulb@84 | 216 | In situations where a callable would normally be used in conjunction with the |
paulb@84 | 217 | Python built-in map function, an alternative solution can be adopted by using |
paulb@84 | 218 | the pmap function: |
paulb@84 | 219 | |
paulb@84 | 220 | pprocess.pmap(fn, sequence) |
paulb@84 | 221 | |
paulb@84 | 222 | Here, the sequence would have to contain elements that each contain the required |
paulb@92 | 223 | parameters of the specified callable, fn. Note that the callable does not need |
paulb@92 | 224 | to be a parallel-aware function which has a channel argument: the pmap function |
paulb@92 | 225 | automatically wraps the given callable internally. |
paulb@84 | 226 | |
paulb@40 | 227 | Signals and Waiting |
paulb@40 | 228 | ------------------- |
paulb@40 | 229 | |
paulb@40 | 230 | When created/child processes terminate, one would typically want to be informed |
paulb@40 | 231 | of such conditions using a signal handler. Unfortunately, Python seems to have |
paulb@40 | 232 | issues with restartable reads from file descriptors when interrupted by signals: |
paulb@40 | 233 | |
paulb@40 | 234 | http://mail.python.org/pipermail/python-dev/2002-September/028572.html |
paulb@40 | 235 | http://twistedmatrix.com/bugs/issue733 |
paulb@40 | 236 | |
paulb@40 | 237 | Select and Poll |
paulb@40 | 238 | --------------- |
paulb@40 | 239 | |
paulb@40 | 240 | The exact combination of conditions indicating closed pipes remains relatively |
paulb@40 | 241 | obscure. Here is a message/thread describing them (in the context of another |
paulb@40 | 242 | topic): |
paulb@40 | 243 | |
paulb@40 | 244 | http://twistedmatrix.com/pipermail/twisted-python/2005-February/009666.html |
paulb@40 | 245 | |
paulb@47 | 246 | It would seem, from using sockets and from studying the asyncore module, that |
paulb@40 | 247 | sockets are more predictable than pipes. |
paulb@58 | 248 | |
paulb@58 | 249 | Notes about poll implementations can be found here: |
paulb@58 | 250 | |
paulb@58 | 251 | http://www.greenend.org.uk/rjk/2001/06/poll.html |
paulb@40 | 252 | """ |
paulb@40 | 253 | |
paulb@99 | 254 | __version__ = "0.3" |
paulb@40 | 255 | |
paulb@40 | 256 | import os |
paulb@40 | 257 | import sys |
paulb@40 | 258 | import select |
paulb@40 | 259 | import socket |
paulb@40 | 260 | |
paulb@40 | 261 | try: |
paulb@40 | 262 | import cPickle as pickle |
paulb@40 | 263 | except ImportError: |
paulb@40 | 264 | import pickle |
paulb@40 | 265 | |
paulb@84 | 266 | # Communications. |
paulb@84 | 267 | |
paulb@40 | 268 | class AcknowledgementError(Exception): |
paulb@40 | 269 | pass |
paulb@40 | 270 | |
paulb@40 | 271 | class Channel: |
paulb@40 | 272 | |
paulb@40 | 273 | "A communications channel." |
paulb@40 | 274 | |
paulb@40 | 275 | def __init__(self, pid, read_pipe, write_pipe): |
paulb@40 | 276 | |
paulb@40 | 277 | """ |
paulb@40 | 278 | Initialise the channel with a process identifier 'pid', a 'read_pipe' |
paulb@40 | 279 | from which messages will be received, and a 'write_pipe' into which |
paulb@40 | 280 | messages will be sent. |
paulb@40 | 281 | """ |
paulb@40 | 282 | |
paulb@40 | 283 | self.pid = pid |
paulb@40 | 284 | self.read_pipe = read_pipe |
paulb@40 | 285 | self.write_pipe = write_pipe |
paulb@40 | 286 | self.closed = 0 |
paulb@40 | 287 | |
paulb@40 | 288 | def __del__(self): |
paulb@40 | 289 | |
paulb@40 | 290 | # Since signals don't work well with I/O, we close pipes and wait for |
paulb@40 | 291 | # created processes upon finalisation. |
paulb@40 | 292 | |
paulb@40 | 293 | self.close() |
paulb@40 | 294 | |
paulb@40 | 295 | def close(self): |
paulb@40 | 296 | |
paulb@40 | 297 | "Explicitly close the channel." |
paulb@40 | 298 | |
paulb@40 | 299 | if not self.closed: |
paulb@40 | 300 | self.closed = 1 |
paulb@40 | 301 | self.read_pipe.close() |
paulb@40 | 302 | self.write_pipe.close() |
paulb@40 | 303 | #self.wait(os.WNOHANG) |
paulb@40 | 304 | |
paulb@40 | 305 | def wait(self, options=0): |
paulb@40 | 306 | |
paulb@40 | 307 | "Wait for the created process, if any, to exit." |
paulb@40 | 308 | |
paulb@40 | 309 | if self.pid != 0: |
paulb@40 | 310 | try: |
paulb@40 | 311 | os.waitpid(self.pid, options) |
paulb@40 | 312 | except OSError: |
paulb@40 | 313 | pass |
paulb@40 | 314 | |
paulb@40 | 315 | def _send(self, obj): |
paulb@40 | 316 | |
paulb@40 | 317 | "Send the given object 'obj' through the channel." |
paulb@40 | 318 | |
paulb@40 | 319 | pickle.dump(obj, self.write_pipe) |
paulb@40 | 320 | self.write_pipe.flush() |
paulb@40 | 321 | |
paulb@40 | 322 | def send(self, obj): |
paulb@40 | 323 | |
paulb@40 | 324 | """ |
paulb@40 | 325 | Send the given object 'obj' through the channel. Then wait for an |
paulb@40 | 326 | acknowledgement. (The acknowledgement makes the caller wait, thus |
paulb@40 | 327 | preventing processes from exiting and disrupting the communications |
paulb@40 | 328 | channel and losing data.) |
paulb@40 | 329 | """ |
paulb@40 | 330 | |
paulb@40 | 331 | self._send(obj) |
paulb@40 | 332 | if self._receive() != "OK": |
paulb@40 | 333 | raise AcknowledgementError, obj |
paulb@40 | 334 | |
paulb@40 | 335 | def _receive(self): |
paulb@40 | 336 | |
paulb@40 | 337 | "Receive an object through the channel, returning the object." |
paulb@40 | 338 | |
paulb@40 | 339 | obj = pickle.load(self.read_pipe) |
paulb@40 | 340 | if isinstance(obj, Exception): |
paulb@40 | 341 | raise obj |
paulb@40 | 342 | else: |
paulb@40 | 343 | return obj |
paulb@40 | 344 | |
paulb@40 | 345 | def receive(self): |
paulb@40 | 346 | |
paulb@40 | 347 | """ |
paulb@40 | 348 | Receive an object through the channel, returning the object. Send an |
paulb@40 | 349 | acknowledgement of receipt. (The acknowledgement makes the sender wait, |
paulb@40 | 350 | thus preventing processes from exiting and disrupting the communications |
paulb@40 | 351 | channel and losing data.) |
paulb@40 | 352 | """ |
paulb@40 | 353 | |
paulb@40 | 354 | try: |
paulb@40 | 355 | obj = self._receive() |
paulb@40 | 356 | return obj |
paulb@40 | 357 | finally: |
paulb@40 | 358 | self._send("OK") |
paulb@40 | 359 | |
paulb@84 | 360 | # Management of processes and communications. |
paulb@84 | 361 | |
paulb@40 | 362 | class Exchange: |
paulb@40 | 363 | |
paulb@40 | 364 | """ |
paulb@40 | 365 | A communications exchange that can be used to detect channels which are |
paulb@67 | 366 | ready to communicate. Subclasses of this class can define the 'store_data' |
paulb@67 | 367 | method in order to enable the 'add_wait', 'wait' and 'finish' methods. |
paulb@40 | 368 | """ |
paulb@40 | 369 | |
paulb@116 | 370 | def __init__(self, channels=None, limit=None, reuse=0, autoclose=1): |
paulb@40 | 371 | |
paulb@40 | 372 | """ |
paulb@67 | 373 | Initialise the exchange with an optional list of 'channels'. |
paulb@67 | 374 | |
paulb@67 | 375 | If the optional 'limit' is specified, restrictions on the addition of |
paulb@67 | 376 | new channels can be enforced and observed through the 'add_wait', 'wait' |
paulb@67 | 377 | and 'finish' methods. To make use of these methods, create a subclass of |
paulb@67 | 378 | this class and define a working 'store_data' method. |
paulb@67 | 379 | |
paulb@116 | 380 | If the optional 'reuse' parameter is set to a true value, channels and |
paulb@116 | 381 | processes will be reused for waiting computations. |
paulb@116 | 382 | |
paulb@67 | 383 | If the optional 'autoclose' parameter is set to a false value, channels |
paulb@67 | 384 | will not be closed automatically when they are removed from the exchange |
paulb@67 | 385 | - by default they are closed when removed. |
paulb@40 | 386 | """ |
paulb@40 | 387 | |
paulb@67 | 388 | self.limit = limit |
paulb@116 | 389 | self.reuse = reuse |
paulb@116 | 390 | self.autoclose = autoclose |
paulb@99 | 391 | self.waiting = [] |
paulb@40 | 392 | self.readables = {} |
paulb@58 | 393 | self.removed = [] |
paulb@40 | 394 | self.poller = select.poll() |
paulb@40 | 395 | for channel in channels or []: |
paulb@40 | 396 | self.add(channel) |
paulb@40 | 397 | |
paulb@40 | 398 | def add(self, channel): |
paulb@40 | 399 | |
paulb@40 | 400 | "Add the given 'channel' to the exchange." |
paulb@40 | 401 | |
paulb@40 | 402 | self.readables[channel.read_pipe.fileno()] = channel |
paulb@40 | 403 | self.poller.register(channel.read_pipe.fileno(), select.POLLIN | select.POLLHUP | select.POLLNVAL | select.POLLERR) |
paulb@40 | 404 | |
paulb@40 | 405 | def active(self): |
paulb@40 | 406 | |
paulb@40 | 407 | "Return a list of active channels." |
paulb@40 | 408 | |
paulb@40 | 409 | return self.readables.values() |
paulb@40 | 410 | |
paulb@40 | 411 | def ready(self, timeout=None): |
paulb@40 | 412 | |
paulb@40 | 413 | """ |
paulb@40 | 414 | Wait for a period of time specified by the optional 'timeout' (or until |
paulb@40 | 415 | communication is possible) and return a list of channels which are ready |
paulb@40 | 416 | to be read from. |
paulb@40 | 417 | """ |
paulb@40 | 418 | |
paulb@40 | 419 | fds = self.poller.poll(timeout) |
paulb@40 | 420 | readables = [] |
paulb@58 | 421 | self.removed = [] |
paulb@58 | 422 | |
paulb@40 | 423 | for fd, status in fds: |
paulb@40 | 424 | channel = self.readables[fd] |
paulb@55 | 425 | removed = 0 |
paulb@40 | 426 | |
paulb@40 | 427 | # Remove ended/error channels. |
paulb@40 | 428 | |
paulb@40 | 429 | if status & (select.POLLHUP | select.POLLNVAL | select.POLLERR): |
paulb@40 | 430 | self.remove(channel) |
paulb@58 | 431 | self.removed.append(channel) |
paulb@55 | 432 | removed = 1 |
paulb@40 | 433 | |
paulb@40 | 434 | # Record readable channels. |
paulb@40 | 435 | |
paulb@55 | 436 | if status & select.POLLIN: |
paulb@55 | 437 | if not (removed and self.autoclose): |
paulb@55 | 438 | readables.append(channel) |
paulb@40 | 439 | |
paulb@40 | 440 | return readables |
paulb@40 | 441 | |
paulb@40 | 442 | def remove(self, channel): |
paulb@40 | 443 | |
paulb@40 | 444 | """ |
paulb@40 | 445 | Remove the given 'channel' from the exchange. |
paulb@40 | 446 | """ |
paulb@40 | 447 | |
paulb@40 | 448 | del self.readables[channel.read_pipe.fileno()] |
paulb@40 | 449 | self.poller.unregister(channel.read_pipe.fileno()) |
paulb@40 | 450 | if self.autoclose: |
paulb@40 | 451 | channel.close() |
paulb@40 | 452 | channel.wait() |
paulb@40 | 453 | |
paulb@67 | 454 | # Enhanced exchange methods involving channel limits. |
paulb@67 | 455 | |
paulb@67 | 456 | def add_wait(self, channel): |
paulb@67 | 457 | |
paulb@67 | 458 | """ |
paulb@67 | 459 | Add the given 'channel' to the exchange, waiting if the limit on active |
paulb@67 | 460 | channels would be exceeded by adding the channel. |
paulb@67 | 461 | """ |
paulb@67 | 462 | |
paulb@67 | 463 | self.wait() |
paulb@67 | 464 | self.add(channel) |
paulb@67 | 465 | |
paulb@67 | 466 | def wait(self): |
paulb@67 | 467 | |
paulb@67 | 468 | """ |
paulb@67 | 469 | Test for the limit on channels, blocking and reading incoming data until |
paulb@67 | 470 | the number of channels is below the limit. |
paulb@67 | 471 | """ |
paulb@67 | 472 | |
paulb@67 | 473 | # If limited, block until channels have been closed. |
paulb@67 | 474 | |
paulb@67 | 475 | while self.limit is not None and len(self.active()) >= self.limit: |
paulb@67 | 476 | self.store() |
paulb@67 | 477 | |
paulb@116 | 478 | def start_waiting(self, channel): |
paulb@99 | 479 | |
paulb@99 | 480 | """ |
paulb@116 | 481 | Start a waiting process given the reception of data on the given |
paulb@116 | 482 | 'channel'. |
paulb@99 | 483 | """ |
paulb@99 | 484 | |
paulb@99 | 485 | if self.waiting: |
paulb@99 | 486 | callable, args, kw = self.waiting.pop() |
paulb@116 | 487 | |
paulb@116 | 488 | # Try and reuse existing channels if possible. |
paulb@116 | 489 | |
paulb@116 | 490 | if self.reuse: |
paulb@116 | 491 | channel.send((args, kw)) |
paulb@116 | 492 | else: |
paulb@116 | 493 | self.add(start(callable, *args, **kw)) |
paulb@116 | 494 | |
paulb@116 | 495 | # Where channels are being reused, but where no processes are waiting |
paulb@116 | 496 | # any more, send a special value to tell them to quit. |
paulb@116 | 497 | |
paulb@116 | 498 | elif self.reuse: |
paulb@116 | 499 | channel.send(None) |
paulb@99 | 500 | |
paulb@67 | 501 | def finish(self): |
paulb@67 | 502 | |
paulb@67 | 503 | """ |
paulb@67 | 504 | Finish the use of the exchange by waiting for all channels to complete. |
paulb@67 | 505 | """ |
paulb@67 | 506 | |
paulb@67 | 507 | while self.active(): |
paulb@67 | 508 | self.store() |
paulb@67 | 509 | |
paulb@67 | 510 | def store(self): |
paulb@67 | 511 | |
paulb@67 | 512 | "For each ready channel, process the incoming data." |
paulb@67 | 513 | |
paulb@67 | 514 | for channel in self.ready(): |
paulb@67 | 515 | self.store_data(channel) |
paulb@116 | 516 | self.start_waiting(channel) |
paulb@67 | 517 | |
paulb@67 | 518 | def store_data(self, channel): |
paulb@67 | 519 | |
paulb@67 | 520 | """ |
paulb@67 | 521 | Store incoming data from the specified 'channel'. In subclasses of this |
paulb@67 | 522 | class, such data could be stored using instance attributes. |
paulb@67 | 523 | """ |
paulb@67 | 524 | |
paulb@67 | 525 | raise NotImplementedError, "store_data" |
paulb@67 | 526 | |
paulb@79 | 527 | # Convenience methods. |
paulb@79 | 528 | |
paulb@84 | 529 | def start(self, callable, *args, **kw): |
paulb@79 | 530 | |
paulb@79 | 531 | """ |
paulb@79 | 532 | Using pprocess.start, create a new process for the given 'callable' |
paulb@79 | 533 | using any additional arguments provided. Then, monitor the channel |
paulb@79 | 534 | created between this process and the created process. |
paulb@79 | 535 | """ |
paulb@79 | 536 | |
paulb@99 | 537 | if self.limit is not None and len(self.active()) >= self.limit: |
paulb@99 | 538 | self.waiting.insert(0, (callable, args, kw)) |
paulb@99 | 539 | return |
paulb@99 | 540 | |
paulb@84 | 541 | self.add_wait(start(callable, *args, **kw)) |
paulb@84 | 542 | |
paulb@97 | 543 | def create(self): |
paulb@97 | 544 | |
paulb@97 | 545 | """ |
paulb@97 | 546 | Using pprocess.create, create a new process and return the created |
paulb@97 | 547 | communications channel to the created process. In the creating process, |
paulb@97 | 548 | return None - the channel receiving data from the created process will |
paulb@97 | 549 | be automatically managed by this exchange. |
paulb@97 | 550 | """ |
paulb@97 | 551 | |
paulb@97 | 552 | channel = create() |
paulb@97 | 553 | if channel.pid == 0: |
paulb@97 | 554 | return channel |
paulb@97 | 555 | else: |
paulb@97 | 556 | self.add_wait(channel) |
paulb@97 | 557 | return None |
paulb@97 | 558 | |
paulb@84 | 559 | def manage(self, callable): |
paulb@84 | 560 | |
paulb@84 | 561 | """ |
paulb@84 | 562 | Wrap the given 'callable' in an object which can then be called in the |
paulb@84 | 563 | same way as 'callable', but with new processes and communications |
paulb@84 | 564 | managed automatically. |
paulb@84 | 565 | """ |
paulb@84 | 566 | |
paulb@84 | 567 | return ManagedCallable(callable, self) |
paulb@84 | 568 | |
paulb@84 | 569 | class ManagedCallable: |
paulb@84 | 570 | |
paulb@84 | 571 | "A callable managed by an exchange." |
paulb@84 | 572 | |
paulb@84 | 573 | def __init__(self, callable, exchange): |
paulb@84 | 574 | |
paulb@84 | 575 | """ |
paulb@84 | 576 | Wrap the given 'callable', using the given 'exchange' to monitor the |
paulb@84 | 577 | channels created for communications between this and the created |
paulb@94 | 578 | processes. Note that the 'callable' must be parallel-aware (that is, |
paulb@94 | 579 | have a 'channel' parameter). Use the MakeParallel class to wrap other |
paulb@94 | 580 | kinds of callable objects. |
paulb@84 | 581 | """ |
paulb@84 | 582 | |
paulb@84 | 583 | self.callable = callable |
paulb@84 | 584 | self.exchange = exchange |
paulb@84 | 585 | |
paulb@84 | 586 | def __call__(self, *args, **kw): |
paulb@84 | 587 | |
paulb@84 | 588 | "Invoke the callable with the supplied arguments." |
paulb@84 | 589 | |
paulb@84 | 590 | self.exchange.start(self.callable, *args, **kw) |
paulb@84 | 591 | |
paulb@84 | 592 | # Abstractions and utilities. |
paulb@84 | 593 | |
paulb@84 | 594 | class Map(Exchange): |
paulb@84 | 595 | |
paulb@84 | 596 | "An exchange which can be used like the built-in 'map' function." |
paulb@84 | 597 | |
paulb@107 | 598 | def __init__(self, *args, **kw): |
paulb@107 | 599 | Exchange.__init__(self, *args, **kw) |
paulb@107 | 600 | self.init() |
paulb@107 | 601 | |
paulb@107 | 602 | def init(self): |
paulb@107 | 603 | |
paulb@107 | 604 | "Remember the channel addition order to order output." |
paulb@107 | 605 | |
paulb@107 | 606 | self.channel_number = 0 |
paulb@107 | 607 | self.channels = {} |
paulb@107 | 608 | self.results = [] |
paulb@107 | 609 | |
paulb@84 | 610 | def add(self, channel): |
paulb@84 | 611 | |
paulb@84 | 612 | "Add the given 'channel' to the exchange." |
paulb@84 | 613 | |
paulb@84 | 614 | Exchange.add(self, channel) |
paulb@92 | 615 | self.channels[channel] = self.channel_number |
paulb@92 | 616 | self.channel_number += 1 |
paulb@84 | 617 | |
paulb@107 | 618 | def start(self, callable, *args, **kw): |
paulb@107 | 619 | |
paulb@107 | 620 | """ |
paulb@107 | 621 | Using pprocess.start, create a new process for the given 'callable' |
paulb@107 | 622 | using any additional arguments provided. Then, monitor the channel |
paulb@107 | 623 | created between this process and the created process. |
paulb@107 | 624 | """ |
paulb@107 | 625 | |
paulb@107 | 626 | self.results.append(None) # placeholder |
paulb@107 | 627 | Exchange.start(self, callable, *args, **kw) |
paulb@107 | 628 | |
paulb@110 | 629 | def create(self): |
paulb@110 | 630 | |
paulb@110 | 631 | """ |
paulb@110 | 632 | Using pprocess.create, create a new process and return the created |
paulb@110 | 633 | communications channel to the created process. In the creating process, |
paulb@110 | 634 | return None - the channel receiving data from the created process will |
paulb@110 | 635 | be automatically managed by this exchange. |
paulb@110 | 636 | """ |
paulb@110 | 637 | |
paulb@110 | 638 | self.results.append(None) # placeholder |
paulb@110 | 639 | return Exchange.create(self) |
paulb@110 | 640 | |
paulb@84 | 641 | def __call__(self, callable, sequence): |
paulb@84 | 642 | |
paulb@89 | 643 | "Wrap and invoke 'callable' for each element in the 'sequence'." |
paulb@89 | 644 | |
paulb@92 | 645 | if not isinstance(callable, MakeParallel): |
paulb@92 | 646 | wrapped = MakeParallel(callable) |
paulb@92 | 647 | else: |
paulb@92 | 648 | wrapped = callable |
paulb@84 | 649 | |
paulb@107 | 650 | self.init() |
paulb@84 | 651 | |
paulb@107 | 652 | # Start processes for each element in the sequence. |
paulb@84 | 653 | |
paulb@84 | 654 | for i in sequence: |
paulb@92 | 655 | self.start(wrapped, i) |
paulb@107 | 656 | |
paulb@107 | 657 | # Access to the results occurs through this object. |
paulb@107 | 658 | |
paulb@107 | 659 | return self |
paulb@84 | 660 | |
paulb@107 | 661 | def __getitem__(self, i): |
paulb@107 | 662 | self.finish() |
paulb@107 | 663 | return self.results[i] |
paulb@84 | 664 | |
paulb@107 | 665 | def __iter__(self): |
paulb@107 | 666 | self.finish() |
paulb@107 | 667 | return iter(self.results) |
paulb@84 | 668 | |
paulb@84 | 669 | def store_data(self, channel): |
paulb@84 | 670 | |
paulb@84 | 671 | "Accumulate the incoming data, associating results with channels." |
paulb@84 | 672 | |
paulb@84 | 673 | data = channel.receive() |
paulb@92 | 674 | self.results[self.channels[channel]] = data |
paulb@92 | 675 | del self.channels[channel] |
paulb@84 | 676 | |
paulb@97 | 677 | class Queue(Exchange): |
paulb@97 | 678 | |
paulb@97 | 679 | """ |
paulb@97 | 680 | An exchange acting as a queue, making data from created processes available |
paulb@97 | 681 | in the order in which it is received. |
paulb@97 | 682 | """ |
paulb@97 | 683 | |
paulb@97 | 684 | def __init__(self, *args, **kw): |
paulb@97 | 685 | Exchange.__init__(self, *args, **kw) |
paulb@97 | 686 | self.queue = [] |
paulb@97 | 687 | |
paulb@97 | 688 | def store_data(self, channel): |
paulb@97 | 689 | |
paulb@97 | 690 | "Accumulate the incoming data, associating results with channels." |
paulb@97 | 691 | |
paulb@97 | 692 | data = channel.receive() |
paulb@97 | 693 | self.queue.insert(0, data) |
paulb@97 | 694 | |
paulb@97 | 695 | def __iter__(self): |
paulb@97 | 696 | return self |
paulb@97 | 697 | |
paulb@97 | 698 | def next(self): |
paulb@97 | 699 | |
paulb@97 | 700 | "Return the next element in the queue." |
paulb@97 | 701 | |
paulb@97 | 702 | if self.queue: |
paulb@97 | 703 | return self.queue.pop() |
paulb@97 | 704 | while self.active(): |
paulb@97 | 705 | self.store() |
paulb@97 | 706 | if self.queue: |
paulb@97 | 707 | return self.queue.pop() |
paulb@97 | 708 | else: |
paulb@97 | 709 | raise StopIteration |
paulb@97 | 710 | |
paulb@84 | 711 | class MakeParallel: |
paulb@84 | 712 | |
paulb@84 | 713 | "A wrapper around functions making them able to communicate results." |
paulb@84 | 714 | |
paulb@84 | 715 | def __init__(self, callable): |
paulb@84 | 716 | |
paulb@94 | 717 | """ |
paulb@94 | 718 | Initialise the wrapper with the given 'callable'. This object will then |
paulb@94 | 719 | be able to accept a 'channel' parameter when invoked, and to forward the |
paulb@94 | 720 | result of the given 'callable' via the channel provided back to the |
paulb@94 | 721 | invoking process. |
paulb@94 | 722 | """ |
paulb@84 | 723 | |
paulb@84 | 724 | self.callable = callable |
paulb@84 | 725 | |
paulb@84 | 726 | def __call__(self, channel, *args, **kw): |
paulb@84 | 727 | |
paulb@84 | 728 | "Invoke the callable and return its result via the given 'channel'." |
paulb@84 | 729 | |
paulb@84 | 730 | channel.send(self.callable(*args, **kw)) |
paulb@84 | 731 | |
paulb@84 | 732 | # Utility functions. |
paulb@79 | 733 | |
paulb@40 | 734 | def create(): |
paulb@40 | 735 | |
paulb@40 | 736 | """ |
paulb@40 | 737 | Create a new process, returning a communications channel to both the |
paulb@40 | 738 | creating process and the created process. |
paulb@40 | 739 | """ |
paulb@40 | 740 | |
paulb@40 | 741 | parent, child = socket.socketpair() |
paulb@40 | 742 | for s in [parent, child]: |
paulb@40 | 743 | s.setblocking(1) |
paulb@40 | 744 | |
paulb@40 | 745 | pid = os.fork() |
paulb@40 | 746 | if pid == 0: |
paulb@40 | 747 | parent.close() |
paulb@73 | 748 | return Channel(pid, child.makefile("r", 0), child.makefile("w", 0)) |
paulb@40 | 749 | else: |
paulb@40 | 750 | child.close() |
paulb@73 | 751 | return Channel(pid, parent.makefile("r", 0), parent.makefile("w", 0)) |
paulb@40 | 752 | |
paulb@97 | 753 | def exit(channel): |
paulb@97 | 754 | |
paulb@97 | 755 | """ |
paulb@97 | 756 | Terminate a created process, closing the given 'channel'. |
paulb@97 | 757 | """ |
paulb@97 | 758 | |
paulb@97 | 759 | channel.close() |
paulb@97 | 760 | os._exit(0) |
paulb@97 | 761 | |
paulb@84 | 762 | def start(callable, *args, **kw): |
paulb@40 | 763 | |
paulb@40 | 764 | """ |
paulb@40 | 765 | Create a new process which shall start running in the given 'callable'. |
paulb@94 | 766 | Additional arguments to the 'callable' can be given as additional arguments |
paulb@94 | 767 | to this function. |
paulb@94 | 768 | |
paulb@94 | 769 | Return a communications channel to the creating process. For the created |
paulb@94 | 770 | process, supply a channel as the 'channel' parameter in the given 'callable' |
paulb@94 | 771 | so that it may send data back to the creating process. |
paulb@40 | 772 | """ |
paulb@40 | 773 | |
paulb@40 | 774 | channel = create() |
paulb@40 | 775 | if channel.pid == 0: |
paulb@40 | 776 | try: |
paulb@40 | 777 | try: |
paulb@84 | 778 | callable(channel, *args, **kw) |
paulb@40 | 779 | except: |
paulb@40 | 780 | exc_type, exc_value, exc_traceback = sys.exc_info() |
paulb@40 | 781 | channel.send(exc_value) |
paulb@40 | 782 | finally: |
paulb@99 | 783 | exit(channel) |
paulb@40 | 784 | else: |
paulb@40 | 785 | return channel |
paulb@40 | 786 | |
paulb@40 | 787 | def waitall(): |
paulb@40 | 788 | |
paulb@40 | 789 | "Wait for all created processes to terminate." |
paulb@40 | 790 | |
paulb@40 | 791 | try: |
paulb@40 | 792 | while 1: |
paulb@40 | 793 | os.wait() |
paulb@40 | 794 | except OSError: |
paulb@40 | 795 | pass |
paulb@40 | 796 | |
paulb@89 | 797 | def pmap(callable, sequence, limit=None): |
paulb@84 | 798 | |
paulb@89 | 799 | """ |
paulb@89 | 800 | A parallel version of the built-in map function with an optional process |
paulb@94 | 801 | 'limit'. The given 'callable' should not be parallel-aware (that is, have a |
paulb@94 | 802 | 'channel' parameter) since it will be wrapped for parallel communications |
paulb@94 | 803 | before being invoked. |
paulb@94 | 804 | |
paulb@94 | 805 | Return the processed 'sequence' where each element in the sequence is |
paulb@94 | 806 | processed by a different process. |
paulb@89 | 807 | """ |
paulb@84 | 808 | |
paulb@89 | 809 | mymap = Map(limit=limit) |
paulb@84 | 810 | return mymap(callable, sequence) |
paulb@84 | 811 | |
paulb@40 | 812 | # vim: tabstop=4 expandtab shiftwidth=4 |