Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #47321

Re: Thread-safe way to prevent decorator from being nested

From Peter Otten <__peter__@web.de>
Subject Re: Thread-safe way to prevent decorator from being nested
Date 2013-06-07 11:07 +0200
Organization None
References <21b0b719-cdf9-4475-81ac-a429a1e65907@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.2847.1370596054.3114.python-list@python.org> (permalink)

Show all headers | View raw


Michael wrote:

> I'm writing a decorator that I never want to be nested. Following from the
> answer on my StackOverflow question
> (http://stackoverflow.com/a/16905779/106244), I've adapted it to the
> following.
> 
> Can anyone spot any issues with this? It'll be run in a multi-threaded
> environment serving Django requests and also be a part of Celery tasks.

I'm not sure I understand what you are trying to do, but this

>             if not within_special_wrapper():
>                 with flag():

looks suspiciously like race condition.

>    thread_safe_globals = threading.local()

I'm not an expert in the area, but I think you need a lock, something like

class NestingError(Exception):
    pass

nest_lock = threading.Lock()

def my_special_wrapper(f):
    @wraps(f)
    def internal(*args, **kwargs):
        if nest_lock.acquire(False): # non-blocking
            try:
                f(*args, **kwargs)
            finally:
                nest_lock.release()
        else:
            raise NestingError
    return internal

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

Thread-safe way to prevent decorator from being nested Michael <mw@d3i.com> - 2013-06-06 09:48 -0700
  Re: Thread-safe way to prevent decorator from being nested Peter Otten <__peter__@web.de> - 2013-06-07 11:07 +0200

csiph-web