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@40 | 55 | channel = 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@40 | 63 | else: |
paulb@40 | 64 | # This code is run by the creating/calling process. |
paulb@40 | 65 | # Read from and write to the channel to communicate with the created |
paulb@40 | 66 | # process. |
paulb@40 | 67 | ... |
paulb@40 | 68 | |
paulb@40 | 69 | Message Exchanges |
paulb@40 | 70 | ----------------- |
paulb@40 | 71 | |
paulb@40 | 72 | When creating many processes, each providing results for the consumption of the |
paulb@40 | 73 | main process, the collection of those results in an efficient fashion can be |
paulb@40 | 74 | problematic: if some processes take longer than others, and if we decide to read |
paulb@40 | 75 | from those processes when they are not ready instead of other processes which |
paulb@40 | 76 | are ready, the whole activity will take much longer than necessary. |
paulb@40 | 77 | |
paulb@40 | 78 | One solution to the problem of knowing when to read from channels is to create |
paulb@40 | 79 | an Exchange object, optionally initialising it with a list of channels through |
paulb@40 | 80 | which data is expected to arrive: |
paulb@40 | 81 | |
paulb@79 | 82 | exchange = pprocess.Exchange() # populate the exchange later |
paulb@79 | 83 | exchange = pprocess.Exchange(channels) # populate the exchange with channels |
paulb@40 | 84 | |
paulb@40 | 85 | We can add channels to the exchange using the add method: |
paulb@40 | 86 | |
paulb@40 | 87 | exchange.add(channel) |
paulb@40 | 88 | |
paulb@40 | 89 | To test whether an exchange is active - that is, whether it is actually |
paulb@40 | 90 | monitoring any channels - we can use the active method which returns all |
paulb@40 | 91 | channels being monitored by the exchange: |
paulb@40 | 92 | |
paulb@40 | 93 | channels = exchange.active() |
paulb@40 | 94 | |
paulb@40 | 95 | We may then check the exchange to see whether any data is ready to be received; |
paulb@40 | 96 | for example: |
paulb@40 | 97 | |
paulb@40 | 98 | for channel in exchange.ready(): |
paulb@40 | 99 | # Read from and write to the channel. |
paulb@40 | 100 | ... |
paulb@40 | 101 | |
paulb@40 | 102 | If we do not wish to wait indefinitely for a list of channels, we can set a |
paulb@40 | 103 | timeout value as an argument to the ready method (as a floating point number |
paulb@40 | 104 | specifying the timeout in seconds, where 0 means a non-blocking poll as stated |
paulb@40 | 105 | in the select module's select function documentation). |
paulb@40 | 106 | |
paulb@67 | 107 | Convenient Message Exchanges |
paulb@67 | 108 | ---------------------------- |
paulb@67 | 109 | |
paulb@67 | 110 | A convenient form of message exchanges can be adopted by defining a subclass of |
paulb@67 | 111 | the Exchange class and defining a particular method: |
paulb@67 | 112 | |
paulb@79 | 113 | class MyExchange(pprocess.Exchange): |
paulb@67 | 114 | def store_data(self, channel): |
paulb@67 | 115 | data = channel.receive() |
paulb@67 | 116 | # Do something with data here. |
paulb@67 | 117 | |
paulb@67 | 118 | The exact operations performed on the received data might be as simple as |
paulb@67 | 119 | storing it on an instance attribute. To make use of the exchange, we would |
paulb@67 | 120 | instantiate it as usual: |
paulb@67 | 121 | |
paulb@67 | 122 | exchange = MyExchange() # populate the exchange later |
paulb@67 | 123 | exchange = MyExchange(limit=10) # set a limit for later population |
paulb@67 | 124 | |
paulb@67 | 125 | The exchange can now be used in a simpler fashion than that shown above. We can |
paulb@67 | 126 | add channels as before using the add method, or we can choose to only add |
paulb@67 | 127 | channels if the specified limit of channels is not exceeded: |
paulb@67 | 128 | |
paulb@67 | 129 | exchange.add(channel) # add a channel as normal |
paulb@67 | 130 | exchange.add_wait(channel) # add a channel, waiting if the limit would be |
paulb@67 | 131 | # exceeded |
paulb@67 | 132 | |
paulb@79 | 133 | We can even start processes and monitor channels without ever handling the |
paulb@79 | 134 | channel ourselves: |
paulb@79 | 135 | |
paulb@79 | 136 | exchange.start(fn, arg1, arg2, named1=value1, named2=value2) |
paulb@79 | 137 | |
paulb@79 | 138 | We can explicitly wait for "free space" for channels by calling the wait method, |
paulb@79 | 139 | although the start and add_wait methods make this less interesting: |
paulb@67 | 140 | |
paulb@67 | 141 | exchange.wait() |
paulb@67 | 142 | |
paulb@67 | 143 | Finally, when finishing the computation, we can choose to merely call the finish |
paulb@67 | 144 | method and have the remaining data processed automatically: |
paulb@67 | 145 | |
paulb@67 | 146 | exchange.finish() |
paulb@67 | 147 | |
paulb@67 | 148 | Clearly, this approach is less flexible but more convenient than the raw message |
paulb@67 | 149 | exchange API as described above. However, it permits much simpler and clearer |
paulb@67 | 150 | code. |
paulb@67 | 151 | |
paulb@84 | 152 | Managed Callables |
paulb@84 | 153 | ----------------- |
paulb@84 | 154 | |
paulb@84 | 155 | A further simplification of the above convenient use of message exchanges |
paulb@84 | 156 | involves the creation of callables (eg. functions) which are automatically |
paulb@88 | 157 | monitored by an exchange. We create such a callable by calling the manage method |
paulb@84 | 158 | on an exchange: |
paulb@84 | 159 | |
paulb@88 | 160 | myfn = exchange.manage(fn) |
paulb@84 | 161 | |
paulb@84 | 162 | This callable can then be invoked instead of using the exchange's start method: |
paulb@84 | 163 | |
paulb@84 | 164 | myfn(arg1, arg2, named1=value1, named2=value2) |
paulb@84 | 165 | |
paulb@84 | 166 | The exchange's finish method can be used as usual to process incoming data. |
paulb@84 | 167 | |
paulb@92 | 168 | Making Existing Functions Parallel |
paulb@92 | 169 | ---------------------------------- |
paulb@92 | 170 | |
paulb@92 | 171 | In making a program parallel, existing functions which only return results can |
paulb@92 | 172 | be manually modified to accept and use channels to communicate results back to |
paulb@92 | 173 | the main process. However, a simple alternative is to use the MakeParallel class |
paulb@92 | 174 | to provide a wrapper around unmodified functions which will return the results |
paulb@92 | 175 | from those functions in the channels provided. For example: |
paulb@92 | 176 | |
paulb@92 | 177 | fn = pprocess.MakeParallel(originalfn) |
paulb@92 | 178 | |
paulb@84 | 179 | Map-style Processing |
paulb@84 | 180 | -------------------- |
paulb@84 | 181 | |
paulb@84 | 182 | In situations where a callable would normally be used in conjunction with the |
paulb@84 | 183 | Python built-in map function, an alternative solution can be adopted by using |
paulb@84 | 184 | the pmap function: |
paulb@84 | 185 | |
paulb@84 | 186 | pprocess.pmap(fn, sequence) |
paulb@84 | 187 | |
paulb@84 | 188 | Here, the sequence would have to contain elements that each contain the required |
paulb@92 | 189 | parameters of the specified callable, fn. Note that the callable does not need |
paulb@92 | 190 | to be a parallel-aware function which has a channel argument: the pmap function |
paulb@92 | 191 | automatically wraps the given callable internally. |
paulb@84 | 192 | |
paulb@40 | 193 | Signals and Waiting |
paulb@40 | 194 | ------------------- |
paulb@40 | 195 | |
paulb@40 | 196 | When created/child processes terminate, one would typically want to be informed |
paulb@40 | 197 | of such conditions using a signal handler. Unfortunately, Python seems to have |
paulb@40 | 198 | issues with restartable reads from file descriptors when interrupted by signals: |
paulb@40 | 199 | |
paulb@40 | 200 | http://mail.python.org/pipermail/python-dev/2002-September/028572.html |
paulb@40 | 201 | http://twistedmatrix.com/bugs/issue733 |
paulb@40 | 202 | |
paulb@40 | 203 | Select and Poll |
paulb@40 | 204 | --------------- |
paulb@40 | 205 | |
paulb@40 | 206 | The exact combination of conditions indicating closed pipes remains relatively |
paulb@40 | 207 | obscure. Here is a message/thread describing them (in the context of another |
paulb@40 | 208 | topic): |
paulb@40 | 209 | |
paulb@40 | 210 | http://twistedmatrix.com/pipermail/twisted-python/2005-February/009666.html |
paulb@40 | 211 | |
paulb@47 | 212 | It would seem, from using sockets and from studying the asyncore module, that |
paulb@40 | 213 | sockets are more predictable than pipes. |
paulb@58 | 214 | |
paulb@58 | 215 | Notes about poll implementations can be found here: |
paulb@58 | 216 | |
paulb@58 | 217 | http://www.greenend.org.uk/rjk/2001/06/poll.html |
paulb@40 | 218 | """ |
paulb@40 | 219 | |
paulb@84 | 220 | __version__ = "0.2.6" |
paulb@40 | 221 | |
paulb@40 | 222 | import os |
paulb@40 | 223 | import sys |
paulb@40 | 224 | import select |
paulb@40 | 225 | import socket |
paulb@40 | 226 | |
paulb@40 | 227 | try: |
paulb@40 | 228 | import cPickle as pickle |
paulb@40 | 229 | except ImportError: |
paulb@40 | 230 | import pickle |
paulb@40 | 231 | |
paulb@84 | 232 | # Communications. |
paulb@84 | 233 | |
paulb@40 | 234 | class AcknowledgementError(Exception): |
paulb@40 | 235 | pass |
paulb@40 | 236 | |
paulb@40 | 237 | class Channel: |
paulb@40 | 238 | |
paulb@40 | 239 | "A communications channel." |
paulb@40 | 240 | |
paulb@40 | 241 | def __init__(self, pid, read_pipe, write_pipe): |
paulb@40 | 242 | |
paulb@40 | 243 | """ |
paulb@40 | 244 | Initialise the channel with a process identifier 'pid', a 'read_pipe' |
paulb@40 | 245 | from which messages will be received, and a 'write_pipe' into which |
paulb@40 | 246 | messages will be sent. |
paulb@40 | 247 | """ |
paulb@40 | 248 | |
paulb@40 | 249 | self.pid = pid |
paulb@40 | 250 | self.read_pipe = read_pipe |
paulb@40 | 251 | self.write_pipe = write_pipe |
paulb@40 | 252 | self.closed = 0 |
paulb@40 | 253 | |
paulb@40 | 254 | def __del__(self): |
paulb@40 | 255 | |
paulb@40 | 256 | # Since signals don't work well with I/O, we close pipes and wait for |
paulb@40 | 257 | # created processes upon finalisation. |
paulb@40 | 258 | |
paulb@40 | 259 | self.close() |
paulb@40 | 260 | |
paulb@40 | 261 | def close(self): |
paulb@40 | 262 | |
paulb@40 | 263 | "Explicitly close the channel." |
paulb@40 | 264 | |
paulb@40 | 265 | if not self.closed: |
paulb@40 | 266 | self.closed = 1 |
paulb@40 | 267 | self.read_pipe.close() |
paulb@40 | 268 | self.write_pipe.close() |
paulb@40 | 269 | #self.wait(os.WNOHANG) |
paulb@40 | 270 | |
paulb@40 | 271 | def wait(self, options=0): |
paulb@40 | 272 | |
paulb@40 | 273 | "Wait for the created process, if any, to exit." |
paulb@40 | 274 | |
paulb@40 | 275 | if self.pid != 0: |
paulb@40 | 276 | try: |
paulb@40 | 277 | os.waitpid(self.pid, options) |
paulb@40 | 278 | except OSError: |
paulb@40 | 279 | pass |
paulb@40 | 280 | |
paulb@40 | 281 | def _send(self, obj): |
paulb@40 | 282 | |
paulb@40 | 283 | "Send the given object 'obj' through the channel." |
paulb@40 | 284 | |
paulb@40 | 285 | pickle.dump(obj, self.write_pipe) |
paulb@40 | 286 | self.write_pipe.flush() |
paulb@40 | 287 | |
paulb@40 | 288 | def send(self, obj): |
paulb@40 | 289 | |
paulb@40 | 290 | """ |
paulb@40 | 291 | Send the given object 'obj' through the channel. Then wait for an |
paulb@40 | 292 | acknowledgement. (The acknowledgement makes the caller wait, thus |
paulb@40 | 293 | preventing processes from exiting and disrupting the communications |
paulb@40 | 294 | channel and losing data.) |
paulb@40 | 295 | """ |
paulb@40 | 296 | |
paulb@40 | 297 | self._send(obj) |
paulb@40 | 298 | if self._receive() != "OK": |
paulb@40 | 299 | raise AcknowledgementError, obj |
paulb@40 | 300 | |
paulb@40 | 301 | def _receive(self): |
paulb@40 | 302 | |
paulb@40 | 303 | "Receive an object through the channel, returning the object." |
paulb@40 | 304 | |
paulb@40 | 305 | obj = pickle.load(self.read_pipe) |
paulb@40 | 306 | if isinstance(obj, Exception): |
paulb@40 | 307 | raise obj |
paulb@40 | 308 | else: |
paulb@40 | 309 | return obj |
paulb@40 | 310 | |
paulb@40 | 311 | def receive(self): |
paulb@40 | 312 | |
paulb@40 | 313 | """ |
paulb@40 | 314 | Receive an object through the channel, returning the object. Send an |
paulb@40 | 315 | acknowledgement of receipt. (The acknowledgement makes the sender wait, |
paulb@40 | 316 | thus preventing processes from exiting and disrupting the communications |
paulb@40 | 317 | channel and losing data.) |
paulb@40 | 318 | """ |
paulb@40 | 319 | |
paulb@40 | 320 | try: |
paulb@40 | 321 | obj = self._receive() |
paulb@40 | 322 | return obj |
paulb@40 | 323 | finally: |
paulb@40 | 324 | self._send("OK") |
paulb@40 | 325 | |
paulb@84 | 326 | # Management of processes and communications. |
paulb@84 | 327 | |
paulb@40 | 328 | class Exchange: |
paulb@40 | 329 | |
paulb@40 | 330 | """ |
paulb@40 | 331 | A communications exchange that can be used to detect channels which are |
paulb@67 | 332 | ready to communicate. Subclasses of this class can define the 'store_data' |
paulb@67 | 333 | method in order to enable the 'add_wait', 'wait' and 'finish' methods. |
paulb@40 | 334 | """ |
paulb@40 | 335 | |
paulb@67 | 336 | def __init__(self, channels=None, limit=None, autoclose=1): |
paulb@40 | 337 | |
paulb@40 | 338 | """ |
paulb@67 | 339 | Initialise the exchange with an optional list of 'channels'. |
paulb@67 | 340 | |
paulb@67 | 341 | If the optional 'limit' is specified, restrictions on the addition of |
paulb@67 | 342 | new channels can be enforced and observed through the 'add_wait', 'wait' |
paulb@67 | 343 | and 'finish' methods. To make use of these methods, create a subclass of |
paulb@67 | 344 | this class and define a working 'store_data' method. |
paulb@67 | 345 | |
paulb@67 | 346 | If the optional 'autoclose' parameter is set to a false value, channels |
paulb@67 | 347 | will not be closed automatically when they are removed from the exchange |
paulb@67 | 348 | - by default they are closed when removed. |
paulb@40 | 349 | """ |
paulb@40 | 350 | |
paulb@67 | 351 | self.limit = limit |
paulb@40 | 352 | self.autoclose = autoclose |
paulb@40 | 353 | self.readables = {} |
paulb@58 | 354 | self.removed = [] |
paulb@40 | 355 | self.poller = select.poll() |
paulb@40 | 356 | for channel in channels or []: |
paulb@40 | 357 | self.add(channel) |
paulb@40 | 358 | |
paulb@40 | 359 | def add(self, channel): |
paulb@40 | 360 | |
paulb@40 | 361 | "Add the given 'channel' to the exchange." |
paulb@40 | 362 | |
paulb@40 | 363 | self.readables[channel.read_pipe.fileno()] = channel |
paulb@40 | 364 | self.poller.register(channel.read_pipe.fileno(), select.POLLIN | select.POLLHUP | select.POLLNVAL | select.POLLERR) |
paulb@40 | 365 | |
paulb@40 | 366 | def active(self): |
paulb@40 | 367 | |
paulb@40 | 368 | "Return a list of active channels." |
paulb@40 | 369 | |
paulb@40 | 370 | return self.readables.values() |
paulb@40 | 371 | |
paulb@40 | 372 | def ready(self, timeout=None): |
paulb@40 | 373 | |
paulb@40 | 374 | """ |
paulb@40 | 375 | Wait for a period of time specified by the optional 'timeout' (or until |
paulb@40 | 376 | communication is possible) and return a list of channels which are ready |
paulb@40 | 377 | to be read from. |
paulb@40 | 378 | """ |
paulb@40 | 379 | |
paulb@40 | 380 | fds = self.poller.poll(timeout) |
paulb@40 | 381 | readables = [] |
paulb@58 | 382 | self.removed = [] |
paulb@58 | 383 | |
paulb@40 | 384 | for fd, status in fds: |
paulb@40 | 385 | channel = self.readables[fd] |
paulb@55 | 386 | removed = 0 |
paulb@40 | 387 | |
paulb@40 | 388 | # Remove ended/error channels. |
paulb@40 | 389 | |
paulb@40 | 390 | if status & (select.POLLHUP | select.POLLNVAL | select.POLLERR): |
paulb@40 | 391 | self.remove(channel) |
paulb@58 | 392 | self.removed.append(channel) |
paulb@55 | 393 | removed = 1 |
paulb@40 | 394 | |
paulb@40 | 395 | # Record readable channels. |
paulb@40 | 396 | |
paulb@55 | 397 | if status & select.POLLIN: |
paulb@55 | 398 | if not (removed and self.autoclose): |
paulb@55 | 399 | readables.append(channel) |
paulb@40 | 400 | |
paulb@40 | 401 | return readables |
paulb@40 | 402 | |
paulb@40 | 403 | def remove(self, channel): |
paulb@40 | 404 | |
paulb@40 | 405 | """ |
paulb@40 | 406 | Remove the given 'channel' from the exchange. |
paulb@40 | 407 | """ |
paulb@40 | 408 | |
paulb@40 | 409 | del self.readables[channel.read_pipe.fileno()] |
paulb@40 | 410 | self.poller.unregister(channel.read_pipe.fileno()) |
paulb@40 | 411 | if self.autoclose: |
paulb@40 | 412 | channel.close() |
paulb@40 | 413 | channel.wait() |
paulb@40 | 414 | |
paulb@67 | 415 | # Enhanced exchange methods involving channel limits. |
paulb@67 | 416 | |
paulb@67 | 417 | def add_wait(self, channel): |
paulb@67 | 418 | |
paulb@67 | 419 | """ |
paulb@67 | 420 | Add the given 'channel' to the exchange, waiting if the limit on active |
paulb@67 | 421 | channels would be exceeded by adding the channel. |
paulb@67 | 422 | """ |
paulb@67 | 423 | |
paulb@67 | 424 | self.wait() |
paulb@67 | 425 | self.add(channel) |
paulb@67 | 426 | |
paulb@67 | 427 | def wait(self): |
paulb@67 | 428 | |
paulb@67 | 429 | """ |
paulb@67 | 430 | Test for the limit on channels, blocking and reading incoming data until |
paulb@67 | 431 | the number of channels is below the limit. |
paulb@67 | 432 | """ |
paulb@67 | 433 | |
paulb@67 | 434 | # If limited, block until channels have been closed. |
paulb@67 | 435 | |
paulb@67 | 436 | while self.limit is not None and len(self.active()) >= self.limit: |
paulb@67 | 437 | self.store() |
paulb@67 | 438 | |
paulb@67 | 439 | def finish(self): |
paulb@67 | 440 | |
paulb@67 | 441 | """ |
paulb@67 | 442 | Finish the use of the exchange by waiting for all channels to complete. |
paulb@67 | 443 | """ |
paulb@67 | 444 | |
paulb@67 | 445 | while self.active(): |
paulb@67 | 446 | self.store() |
paulb@67 | 447 | |
paulb@67 | 448 | def store(self): |
paulb@67 | 449 | |
paulb@67 | 450 | "For each ready channel, process the incoming data." |
paulb@67 | 451 | |
paulb@67 | 452 | for channel in self.ready(): |
paulb@67 | 453 | self.store_data(channel) |
paulb@67 | 454 | |
paulb@67 | 455 | def store_data(self, channel): |
paulb@67 | 456 | |
paulb@67 | 457 | """ |
paulb@67 | 458 | Store incoming data from the specified 'channel'. In subclasses of this |
paulb@67 | 459 | class, such data could be stored using instance attributes. |
paulb@67 | 460 | """ |
paulb@67 | 461 | |
paulb@67 | 462 | raise NotImplementedError, "store_data" |
paulb@67 | 463 | |
paulb@79 | 464 | # Convenience methods. |
paulb@79 | 465 | |
paulb@84 | 466 | def start(self, callable, *args, **kw): |
paulb@79 | 467 | |
paulb@79 | 468 | """ |
paulb@79 | 469 | Using pprocess.start, create a new process for the given 'callable' |
paulb@79 | 470 | using any additional arguments provided. Then, monitor the channel |
paulb@79 | 471 | created between this process and the created process. |
paulb@79 | 472 | """ |
paulb@79 | 473 | |
paulb@84 | 474 | self.add_wait(start(callable, *args, **kw)) |
paulb@84 | 475 | |
paulb@84 | 476 | def manage(self, callable): |
paulb@84 | 477 | |
paulb@84 | 478 | """ |
paulb@84 | 479 | Wrap the given 'callable' in an object which can then be called in the |
paulb@84 | 480 | same way as 'callable', but with new processes and communications |
paulb@84 | 481 | managed automatically. |
paulb@84 | 482 | """ |
paulb@84 | 483 | |
paulb@84 | 484 | return ManagedCallable(callable, self) |
paulb@84 | 485 | |
paulb@84 | 486 | class ManagedCallable: |
paulb@84 | 487 | |
paulb@84 | 488 | "A callable managed by an exchange." |
paulb@84 | 489 | |
paulb@84 | 490 | def __init__(self, callable, exchange): |
paulb@84 | 491 | |
paulb@84 | 492 | """ |
paulb@84 | 493 | Wrap the given 'callable', using the given 'exchange' to monitor the |
paulb@84 | 494 | channels created for communications between this and the created |
paulb@94 | 495 | processes. Note that the 'callable' must be parallel-aware (that is, |
paulb@94 | 496 | have a 'channel' parameter). Use the MakeParallel class to wrap other |
paulb@94 | 497 | kinds of callable objects. |
paulb@84 | 498 | """ |
paulb@84 | 499 | |
paulb@84 | 500 | self.callable = callable |
paulb@84 | 501 | self.exchange = exchange |
paulb@84 | 502 | |
paulb@84 | 503 | def __call__(self, *args, **kw): |
paulb@84 | 504 | |
paulb@84 | 505 | "Invoke the callable with the supplied arguments." |
paulb@84 | 506 | |
paulb@84 | 507 | self.exchange.start(self.callable, *args, **kw) |
paulb@84 | 508 | |
paulb@84 | 509 | # Abstractions and utilities. |
paulb@84 | 510 | |
paulb@84 | 511 | class Map(Exchange): |
paulb@84 | 512 | |
paulb@84 | 513 | "An exchange which can be used like the built-in 'map' function." |
paulb@84 | 514 | |
paulb@84 | 515 | def add(self, channel): |
paulb@84 | 516 | |
paulb@84 | 517 | "Add the given 'channel' to the exchange." |
paulb@84 | 518 | |
paulb@84 | 519 | Exchange.add(self, channel) |
paulb@92 | 520 | self.channels[channel] = self.channel_number |
paulb@92 | 521 | self.channel_number += 1 |
paulb@84 | 522 | |
paulb@84 | 523 | def __call__(self, callable, sequence): |
paulb@84 | 524 | |
paulb@89 | 525 | "Wrap and invoke 'callable' for each element in the 'sequence'." |
paulb@89 | 526 | |
paulb@92 | 527 | if not isinstance(callable, MakeParallel): |
paulb@92 | 528 | wrapped = MakeParallel(callable) |
paulb@92 | 529 | else: |
paulb@92 | 530 | wrapped = callable |
paulb@84 | 531 | |
paulb@84 | 532 | # Remember the channel addition order to order output. |
paulb@84 | 533 | |
paulb@92 | 534 | self.channel_number = 0 |
paulb@92 | 535 | self.channels = {} |
paulb@92 | 536 | self.results = [] |
paulb@84 | 537 | |
paulb@84 | 538 | for i in sequence: |
paulb@92 | 539 | self.results.append(None) # placeholder |
paulb@92 | 540 | self.start(wrapped, i) |
paulb@84 | 541 | self.finish() |
paulb@84 | 542 | |
paulb@92 | 543 | # NOTE: Could return results as they arrive, but we would then need to |
paulb@92 | 544 | # NOTE: return the position of each result in the original sequence. |
paulb@84 | 545 | |
paulb@92 | 546 | return self.results |
paulb@84 | 547 | |
paulb@84 | 548 | def store_data(self, channel): |
paulb@84 | 549 | |
paulb@84 | 550 | "Accumulate the incoming data, associating results with channels." |
paulb@84 | 551 | |
paulb@84 | 552 | data = channel.receive() |
paulb@92 | 553 | self.results[self.channels[channel]] = data |
paulb@92 | 554 | del self.channels[channel] |
paulb@84 | 555 | |
paulb@84 | 556 | class MakeParallel: |
paulb@84 | 557 | |
paulb@84 | 558 | "A wrapper around functions making them able to communicate results." |
paulb@84 | 559 | |
paulb@84 | 560 | def __init__(self, callable): |
paulb@84 | 561 | |
paulb@94 | 562 | """ |
paulb@94 | 563 | Initialise the wrapper with the given 'callable'. This object will then |
paulb@94 | 564 | be able to accept a 'channel' parameter when invoked, and to forward the |
paulb@94 | 565 | result of the given 'callable' via the channel provided back to the |
paulb@94 | 566 | invoking process. |
paulb@94 | 567 | """ |
paulb@84 | 568 | |
paulb@84 | 569 | self.callable = callable |
paulb@84 | 570 | |
paulb@84 | 571 | def __call__(self, channel, *args, **kw): |
paulb@84 | 572 | |
paulb@84 | 573 | "Invoke the callable and return its result via the given 'channel'." |
paulb@84 | 574 | |
paulb@84 | 575 | channel.send(self.callable(*args, **kw)) |
paulb@84 | 576 | |
paulb@84 | 577 | # Utility functions. |
paulb@79 | 578 | |
paulb@40 | 579 | def create(): |
paulb@40 | 580 | |
paulb@40 | 581 | """ |
paulb@40 | 582 | Create a new process, returning a communications channel to both the |
paulb@40 | 583 | creating process and the created process. |
paulb@40 | 584 | """ |
paulb@40 | 585 | |
paulb@40 | 586 | parent, child = socket.socketpair() |
paulb@40 | 587 | for s in [parent, child]: |
paulb@40 | 588 | s.setblocking(1) |
paulb@40 | 589 | |
paulb@40 | 590 | pid = os.fork() |
paulb@40 | 591 | if pid == 0: |
paulb@40 | 592 | parent.close() |
paulb@73 | 593 | return Channel(pid, child.makefile("r", 0), child.makefile("w", 0)) |
paulb@40 | 594 | else: |
paulb@40 | 595 | child.close() |
paulb@73 | 596 | return Channel(pid, parent.makefile("r", 0), parent.makefile("w", 0)) |
paulb@40 | 597 | |
paulb@84 | 598 | def start(callable, *args, **kw): |
paulb@40 | 599 | |
paulb@40 | 600 | """ |
paulb@40 | 601 | Create a new process which shall start running in the given 'callable'. |
paulb@94 | 602 | Additional arguments to the 'callable' can be given as additional arguments |
paulb@94 | 603 | to this function. |
paulb@94 | 604 | |
paulb@94 | 605 | Return a communications channel to the creating process. For the created |
paulb@94 | 606 | process, supply a channel as the 'channel' parameter in the given 'callable' |
paulb@94 | 607 | so that it may send data back to the creating process. |
paulb@40 | 608 | """ |
paulb@40 | 609 | |
paulb@40 | 610 | channel = create() |
paulb@40 | 611 | if channel.pid == 0: |
paulb@40 | 612 | try: |
paulb@40 | 613 | try: |
paulb@84 | 614 | callable(channel, *args, **kw) |
paulb@40 | 615 | except: |
paulb@40 | 616 | exc_type, exc_value, exc_traceback = sys.exc_info() |
paulb@40 | 617 | channel.send(exc_value) |
paulb@40 | 618 | finally: |
paulb@40 | 619 | channel.close() |
paulb@61 | 620 | os._exit(0) |
paulb@40 | 621 | else: |
paulb@40 | 622 | return channel |
paulb@40 | 623 | |
paulb@40 | 624 | def waitall(): |
paulb@40 | 625 | |
paulb@40 | 626 | "Wait for all created processes to terminate." |
paulb@40 | 627 | |
paulb@40 | 628 | try: |
paulb@40 | 629 | while 1: |
paulb@40 | 630 | os.wait() |
paulb@40 | 631 | except OSError: |
paulb@40 | 632 | pass |
paulb@40 | 633 | |
paulb@89 | 634 | def pmap(callable, sequence, limit=None): |
paulb@84 | 635 | |
paulb@89 | 636 | """ |
paulb@89 | 637 | A parallel version of the built-in map function with an optional process |
paulb@94 | 638 | 'limit'. The given 'callable' should not be parallel-aware (that is, have a |
paulb@94 | 639 | 'channel' parameter) since it will be wrapped for parallel communications |
paulb@94 | 640 | before being invoked. |
paulb@94 | 641 | |
paulb@94 | 642 | Return the processed 'sequence' where each element in the sequence is |
paulb@94 | 643 | processed by a different process. |
paulb@89 | 644 | """ |
paulb@84 | 645 | |
paulb@89 | 646 | mymap = Map(limit=limit) |
paulb@84 | 647 | return mymap(callable, sequence) |
paulb@84 | 648 | |
paulb@40 | 649 | # vim: tabstop=4 expandtab shiftwidth=4 |