Re: Error "signal only works in main thread"

Joel Rivera <[email protected]>
Newsgroups gmane.comp.python.cherrypy
Message-ID <20160311204736.53a7a88d@graphene>
Hello Max,

> thanks for your answer! I implemented a plugin for the optimization 
> routines, but it still results in the same error. :/ Are you sure
> plugins run on the main thread?
> 
> Please take a look at the code - did I do anything wrong?
> https://gist.github.com/anonymous/d955db89c8381d052653


I was wrong about the assumption of the plugins and the main thread.
You implemented correctly what I suggested.

But don't despair! I just hacked away a nifty class that can help you.

The full example is in this gist:

https://gist.github.com/cyraxjoe/93bedb7d942e75ac44f7

But I'll copy/paste the relevant class and decorator:


class MainExecutor:
    """Wrap a callable to ensure that the execution takes place on the
    MainThread based on the cherrypy.engine and the 'main' channel.

    For example:

    >>> def sample(arg): return "foo {}".format(arg)
    ...
    >>> mexec = MainExecutor(sample)
    >>> mexec("bar")
    'foo bar'
    >>> mexec("test")
    'foo test'
    """

    def __init__(self, func, bus=cp.engine):
        self.func = func
        self.bus = bus

    def __call__(self, *args, **kwargs):
        results = []
        done_event = threading.Event()
        executable = functools.partial(
            self._execute, results, done_event, *args, **kwargs)
        self.bus.subscribe('main', executable)
        done_event.wait()
        self.bus.unsubscribe('main', executable)
        success, rsp = results
        if success:
            return rsp
        else:
            raise rsp

    def _execute(self, response, done_event, *args, **kwargs):
        try:
            result = self.func(*args, **kwargs)
        except Exception as e:
            response.append(False)
            response.append(e)
        else:
            response.append(True)
            response.append(result)
        finally:
            done_event.set()


def in_main_thread(func):
    """Pretty interface to use the MainExecutor class
    as a decorator and not have the CamelCase on a decorator.
    """
    return MainExecutor(func)


Cheers,
-- 
Rivera²

-- 
You received this message because you are subscribed to the Google Groups "cherrypy-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cherrypy-users+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/[email protected]
To post to this group, send email to cherrypy-users-/JYPxA39Uh5TLH3MbocFF+G/[email protected]
Visit this group at https://groups.google.com/group/cherrypy-users.
For more options, visit https://groups.google.com/d/optout.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.