示例#1
0
class symbol(object):
    """A constant symbol.

    >>> symbol('foo') is symbol('foo')
    True
    >>> symbol('foo')
    <symbol 'foo>

    A slight refinement of the MAGICCOOKIE=object() pattern.  The primary
    advantage of symbol() is its repr().  They are also singletons.

    Repeated calls of symbol('name') will all return the same instance.

    The optional ``doc`` argument assigns to ``__doc__``.  This
    is strictly so that Sphinx autoattr picks up the docstring we want
    (it doesn't appear to pick up the in-module docstring if the datamember
    is in a different module - autoattribute also blows up completely).
    If Sphinx fixes/improves this then we would no longer need
    ``doc`` here.

    """
    symbols = {}
    _lock = threading.Lock()

    def __new__(cls, name, doc=None):
        cls._lock.acquire()
        try:
            sym = cls.symbols.get(name)
            if sym is None:
                cls.symbols[name] = sym = _symbol(name, doc)
            return sym
        finally:
            symbol._lock.release()
示例#2
0
def counter():
    """Return a threadsafe counter function."""

    lock = threading.Lock()
    counter = itertools.count(1L)

    # avoid the 2to3 "next" transformation...
    def _next():
        lock.acquire()
        try:
            return counter.next()
        finally:
            lock.release()

    return _next