PageRenderTime 22ms CodeModel.GetById 10ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 0ms

/circuits/core/futures.py

https://bitbucket.org/prologic/circuits/
Python | 51 lines | 45 code | 1 blank | 5 comment | 0 complexity | db9642478cbedc4fccb2c51784a45d48 MD5 | raw file
 1# Module:   future
 2# Date:     6th February 2010
 3# Author:   James Mills, prologic at shortcircuit dot net dot au
 4
 5"""Futures
 6
 7circuits supports the concept of "future" events. In circuits futures are
 8event handlers that are specially designed to be run in the background
 9either in a Thread or a Process. If you have event handlers that may
10potentially "block" then wrapping them by the @future decorator unblocks
11the bottle-neck caused by the "blocking" event handler(s).
12
13Support for using a Thread or Process pool is also supported by specifying
14an optional `pool` keyword argument and supplying an instance to a
15``circuits.core.pool.Pool``.
16"""
17
18from uuid import uuid4 as uuid
19from functools import update_wrapper
20
21from .values import Value
22from .utils import findcmp
23from .workers import Worker
24from .pools import Pool, Task
25
26
27def future(pool=None):
28    """Decorator to wrap an event handler in a future Task
29
30    This decorator wraps an event handler into a background Task
31    executing the event handler function in the background.
32
33    :param pool: An optional thread/process pool
34    :type pool: Pool
35    """
36
37    def decorate(f):
38        def wrapper(self, event, *args, **kwargs):
39            event.future = True
40            p = getattr(self, "_pool", pool)
41            if p is None:
42                p = findcmp(self.root, Pool)
43            if p is not None:
44                setattr(self, "_pool", p)
45                return self.fire(Task(f, self, *args, **kwargs), target=p)
46            else:
47                return Worker(channel=str(uuid())).fire(
48                        Task(f, self, *args, **kwargs))
49        wrapper.event = True
50        return update_wrapper(wrapper, f)
51    return decorate