Esempio n. 1
0
def run_reactor(in_thread=True):
    """
    Safely run the Twisted reactor
    """
    global reactor
    global _reactor_thread
    
    from osaf.framework.twisted import TwistedThreadPool  # initializes threads

    from twisted.internet import reactor

    if not in_thread:
        if reactor.running:
            raise AssertionError("Reactor is already running")
        for evt in reactor.crash, reactor.disconnectAll:
            reactor.addSystemEventTrigger('during', 'shutdown', evt)
        reactor.run(0)
        return

    if _reactor_thread is None:
        if threading.currentThread().getName() != "MainThread":
            raise AssertionError(
                "can't start reactor thread except from the main thread"
            )
        limbo = [1]
        reactor.addSystemEventTrigger('after', 'startup', limbo.pop)
        _reactor_thread = RepositoryThread(
            name="reactor", target=run_reactor, args=(False,)
        )
        _reactor_thread.setDaemon(True) # let main thread exit even if running
        _reactor_thread.start()

        while limbo and _reactor_thread.isAlive():
            pass   # wait for reactor to start or thread to die (e.g. w/error)

        if not _reactor_thread.isAlive():
            _reactor_thread = None
def run_reactor(in_thread=True):
    """
    Safely run the Twisted reactor
    """
    global reactor
    global _reactor_thread

    from osaf.framework.twisted import TwistedThreadPool  # initializes threads

    from twisted.internet import reactor

    if not in_thread:
        if reactor.running:
            raise AssertionError("Reactor is already running")
        for evt in reactor.crash, reactor.disconnectAll:
            reactor.addSystemEventTrigger('during', 'shutdown', evt)
        reactor.run(0)
        return

    if _reactor_thread is None:
        if threading.currentThread().getName() != "MainThread":
            raise AssertionError(
                "can't start reactor thread except from the main thread")
        limbo = [1]
        reactor.addSystemEventTrigger('after', 'startup', limbo.pop)
        _reactor_thread = RepositoryThread(name="reactor",
                                           target=run_reactor,
                                           args=(False, ))
        _reactor_thread.setDaemon(True)  # let main thread exit even if running
        _reactor_thread.start()

        while limbo and _reactor_thread.isAlive():
            pass  # wait for reactor to start or thread to die (e.g. w/error)

        if not _reactor_thread.isAlive():
            _reactor_thread = None