当前位置: 首页>>代码示例>>Python>>正文


Python ThreadPool.stop方法代码示例

本文整理汇总了Python中twisted.python.threadpool.ThreadPool.stop方法的典型用法代码示例。如果您正苦于以下问题:Python ThreadPool.stop方法的具体用法?Python ThreadPool.stop怎么用?Python ThreadPool.stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twisted.python.threadpool.ThreadPool的用法示例。


在下文中一共展示了ThreadPool.stop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: AddressResolver

# 需要导入模块: from twisted.python.threadpool import ThreadPool [as 别名]
# 或者: from twisted.python.threadpool.ThreadPool import stop [as 别名]
class AddressResolver(object):
    pool = None

    def __init__(self, minthreads=1, maxthreads=4):
        self.pool = ThreadPool(minthreads=minthreads, maxthreads=maxthreads)
        # unclosed ThreadPool leads to reactor hangs at shutdown
        # this is a problem in many situation, so better enforce pool stop here
        reactor.addSystemEventTrigger(
            "before", "shutdown", self.pool.stop
        )

        self.pool.start()

    def get_host_by_name(self, address):
        d = defer.Deferred()

        def func():
            try:
                reactor.callFromThread(
                    d.callback, socket.gethostbyname(address)
                )
            except Exception as e:
                reactor.callFromThread(d.errback, e)

        self.pool.callInThread(func)
        return d

    def close(self):
        self.pool.stop()
开发者ID:UltrosBot,项目名称:Ultros,代码行数:31,代码来源:resolver.py

示例2: FakeReactor

# 需要导入模块: from twisted.python.threadpool import ThreadPool [as 别名]
# 或者: from twisted.python.threadpool.ThreadPool import stop [as 别名]
class FakeReactor(object):
    """
    A fake reactor implementation which just supports enough reactor APIs for
    L{ThreadedResolver}.
    """
    implements(IReactorTime, IReactorThreads)

    def __init__(self):
        self._clock = Clock()
        self.callLater = self._clock.callLater

        self._threadpool = ThreadPool()
        self._threadpool.start()
        self.getThreadPool = lambda: self._threadpool

        self._threadCalls = Queue()


    def callFromThread(self, f, *args, **kwargs):
        self._threadCalls.put((f, args, kwargs))


    def _runThreadCalls(self):
        f, args, kwargs = self._threadCalls.get()
        f(*args, **kwargs)


    def _stop(self):
        self._threadpool.stop()
开发者ID:Almad,项目名称:twisted,代码行数:31,代码来源:test_base.py

示例3: ThreadPoolService

# 需要导入模块: from twisted.python.threadpool import ThreadPool [as 别名]
# 或者: from twisted.python.threadpool.ThreadPool import stop [as 别名]
class ThreadPoolService(Service):
    def __init__(self):
        self.threadpool = ThreadPool()


    def startService(self):
        self.threadpool.start()


    def stopService(self):
        self.threadpool.stop()
开发者ID:ddormer,项目名称:bdm,代码行数:13,代码来源:blood_service.py

示例4: TwistedThreadScheduler

# 需要导入模块: from twisted.python.threadpool import ThreadPool [as 别名]
# 或者: from twisted.python.threadpool.ThreadPool import stop [as 别名]
class TwistedThreadScheduler(BaseScheduler):
    """Run jobs in threads, chaperoned by Twisted."""

    def __init__(self, num_threads, install_signal_handlers=True):
        """Create a new `TwistedThreadScheduler`.

        :param num_threads: The number of threads to allocate to the
          thread pool.
        :type num_threads: int

        :param install_signal_handlers: Whether the Twisted reactor
          should install signal handlers or not. This is intented for
          testing - set to False to avoid layer violations - but may
          be useful in other situations.
        :type install_signal_handlers: bool
        """
        self._thread_pool = ThreadPool(0, num_threads)
        self._install_signal_handlers = install_signal_handlers
        self._jobs = []

    def schedule(self, func, *args, **kwargs):
        self._jobs.append(
            deferToThreadPool(
                reactor, self._thread_pool, func, *args, **kwargs))

    def run(self):
        jobs, self._jobs = self._jobs[:], []
        jobs_done = DeferredList(jobs)
        jobs_done.addBoth(lambda ignore: self._thread_pool.stop())
        jobs_done.addBoth(lambda ignore: reactor.stop())
        reactor.callWhenRunning(self._thread_pool.start)
        reactor.run(self._install_signal_handlers)
开发者ID:pombreda,项目名称:UnnaturalCodeFork,代码行数:34,代码来源:core.py

示例5: ThreadedRunner

# 需要导入模块: from twisted.python.threadpool import ThreadPool [as 别名]
# 或者: from twisted.python.threadpool.ThreadPool import stop [as 别名]
class ThreadedRunner(SimpleRunner):
    """Run tests using a threadpool.
    Uses TwistedPython's thread pool"""
    def __init__(self, result_class):
        from twisted.python.threadpool import ThreadPool

        SimpleRunner.__init__(self, _threadclass(result_class))
        
        self._pool = ThreadPool()
        self._pool.start()

    def run(self, fixture):
        assert not self._done
        self._pool.dispatch(None, fixture, self._result)

    def result(self):
        self._pool.stop()
        return SimpleRunner.result(self)
开发者ID:bhramoss,项目名称:code,代码行数:20,代码来源:recipe-391414.py

示例6: TestDonationAPI

# 需要导入模块: from twisted.python.threadpool import ThreadPool [as 别名]
# 或者: from twisted.python.threadpool.ThreadPool import stop [as 别名]
class TestDonationAPI(TestCase):
    """
    Tests for L{bdm.resource.DonationAPI}.
    """
    def setUp(self):
        self.store = Store()
        self.threadPool = ThreadPool()
        self.threadPool.start()
        self.api = DonationAPI(self.store, 'nothing', self.threadPool)


    def tearDown(self):
        self.threadPool.stop()


    def test_serverStatsSuccess(self):
        """
        L{serverStats} returns the expected dictionary results when passed a
        valid [IP, PORT].
        """
        def _cb(result):
            expected = [{'server_name': 'Test Server',
                         'map': 'testmap',
                         'player_count': 8,
                         'max_players': 16,
                         'online': True,
                         'location': 'ZA'}]
            self.assertEqual(expected, result)

        servers = [['1.1.1.1', 27015, "ZA"]]
        return self.api.serverStats(servers, querier=MockServerQuerier).addCallback(_cb)


    def test_serverStatsOffline(self):
        """
        No exception is raised if the server is inaccesable, and the online
        status is set to C{False}
        """
        def _cb(result):
            expected = [{'server_name': '1.1.1.2', 'online': False, 'location':'ZA'}]
            self.assertEqual(expected, result)

        servers = [['1.1.1.2', 27015, "ZA"]]
        return self.api.serverStats(servers, querier=MockServerQuerier).addCallback(_cb)
开发者ID:ddormer,项目名称:bdm,代码行数:46,代码来源:test_resource.py

示例7: stop

# 需要导入模块: from twisted.python.threadpool import ThreadPool [as 别名]
# 或者: from twisted.python.threadpool.ThreadPool import stop [as 别名]
    def stop(self):
        """
        Flushes any remaining data, closes the underlying files, then stops
        the thread pool.

        .. warning::

            Because this method is usually called when the reactor is
            stopping all file handling happens in the main thread.
        """
        if not self.started or self.joined:
            return

        logger.debug("Logging thread pool is shutting down.")
        self.stopped = True

        for protocol_id in list(self.logs.keys()):
            self.close_log(protocol_id)

        ThreadPool.stop(self)
开发者ID:xlhtc007,项目名称:pyfarm-agent,代码行数:22,代码来源:log.py

示例8: __init__

# 需要导入模块: from twisted.python.threadpool import ThreadPool [as 别名]
# 或者: from twisted.python.threadpool.ThreadPool import stop [as 别名]
    def __init__(self, pool=None,  minthreads=1, maxthreads=4, **kwargs):
        """Creates a twisted aware Session

        Notes
        ~~~~~

        * If you provide both `pool` and `max_workers`, the latter is
          ignored and provided threadpool is used as is.
        """
        requestsSession.__init__(self, **kwargs)
        self.ownPool = False
        if pool is None:
            self.ownPool = True
            pool = ThreadPool(minthreads=minthreads, maxthreads=maxthreads)
            # unclosed ThreadPool leads to reactor hangs at shutdown
            # this is a problem in many situation, so better enforce pool stop here
            reactor.addSystemEventTrigger("before", "shutdown", lambda:pool.stop())
        self.pool = pool
        if self.ownPool:
            pool.start()
开发者ID:jdemaeyer,项目名称:txrequests,代码行数:22,代码来源:sessions.py

示例9: Validator

# 需要导入模块: from twisted.python.threadpool import ThreadPool [as 别名]
# 或者: from twisted.python.threadpool.ThreadPool import stop [as 别名]
class Validator(object):
    DefaultTransactionFamilies = [
        endpoint_registry
    ]

    def __init__(self,
                 gossip_obj,
                 journal_obj,
                 stat_domains,
                 config,
                 windows_service=False,
                 http_port=None,
                 ):
        '''
        Creates a validator.  As a current side-effect, does some
        initialization on it's ledger_obj argumenet
        Args:
            node_obj: (gossip.Node)
            journal_obj: (journal.Journal)
            config: (dict)
            windows_service: (bool)
            http_port: (int)
        '''
        self.status = 'stopped'
        self.config = config
        self.stat_domains = stat_domains

        self.gossip = gossip_obj
        node_obj = gossip_obj.LocalNode
        self._gossip_host = node_obj.NetHost
        self._gossip_port = node_obj.NetAddress

        self._endpoint_host = node_obj.endpoint_host
        self._endpoint_port = node_obj.endpoint_port
        self._endpoint_http_port = http_port

        self.journal = journal_obj

        self.profile = self.config.get('Profile', False)

        if self.profile:
            self.pr = cProfile.Profile()
            self.pr.enable()

        self.windows_service = windows_service

        # flag to indicate that a topology update is in progress
        self._topology_update_in_progress = False
        self.delay_start = self.config['DelayStart']

        # set up signal handlers for shutdown
        if not windows_service:
            signal.signal(signal.SIGTERM, self.handle_shutdown_signal)
            signal.signal(signal.SIGINT, self.handle_shutdown_signal)

        # ---------- Initialize the configuration ----------
        self.initialize_common_configuration()

        # ---------- Initialize the NodeMap ----------
        self.initialize_node_map()

        # ---------- Initialize the Ledger ----------
        self.initialize_ledger_object()

        maxsize = self.config.get("WebPoolSize", 8)
        self.web_thread_pool = ThreadPool(0, maxsize, "WebThreadPool")

    def handle_shutdown_signal(self, signum, frame):
        logger.warn('received shutdown signal')
        self.shutdown()

    def shutdown(self):
        """
        Shutdown the validator. There are several things that need to happen
        on shutdown: 1) disconnect this node from the network, 2) close all the
        databases, and 3) shutdown twisted. We need time for each to finish.
        """
        self.status = 'stopping'
        if self.profile:
            self.pr.create_stats()
            loc = os.path.join(self.config.get('DataDirectory', '/tmp'),
                               '{0}.cprofile'.format(
                                   self.config.get('NodeName',
                                                   str(os.getpid()))))
            self.pr.dump_stats(loc)

        # send the transaction to remove this node from the endpoint
        # registry (or send it to the web server)
        if self.gossip is not None:
            self.unregister_endpoint(self.gossip.LocalNode)

        # Need to wait long enough for all the shutdown packets to be sent out
        reactor.callLater(1.0, self.handle_ledger_shutdown)

    def handle_ledger_shutdown(self):
        self.journal.shutdown()
        self.gossip.shutdown()

        # Need to wait long enough for all the shutdown packets to be sent out
        # if a shutdown packet was the reason for the shutdown
#.........这里部分代码省略.........
开发者ID:jsmitchell,项目名称:sawtooth-core,代码行数:103,代码来源:validator.py

示例10: Validator

# 需要导入模块: from twisted.python.threadpool import ThreadPool [as 别名]
# 或者: from twisted.python.threadpool.ThreadPool import stop [as 别名]
class Validator(object):
    DefaultTransactionFamilies = [
        # IntegerKey,
        endpoint_registry
    ]

    def __init__(self, config, windows_service):
        self.status = 'stopped'
        self.Config = config

        # Parse the listen directives from the configuration so
        # we know what to bind gossip protocol to
        listen_directives = parse_listen_directives(self.Config)

        # If the gossip listen address is 0.0.0.0, then there must be
        # an Endpoint.Host entry as we don't know what to put in the
        # endpoint registry otherwise.
        if listen_directives['gossip'].host == '0.0.0.0' and \
                ('Endpoint' not in self.Config or
                 'Port' not in self.Config['Endpoint']):
            raise Exception(
                'gossip listen address is 0.0.0.0, but endpoint host '
                'missing from configuration')

        self._gossip_host = listen_directives['gossip'].host
        self._gossip_port = listen_directives['gossip'].port

        # The endpoint host/port and HTTP port come from the listen data, but
        # can be overridden by the configuration.
        self._endpoint_host = self._gossip_host
        self._endpoint_port = self._gossip_port
        self._endpoint_http_port = None
        if 'http' in listen_directives:
            self._endpoint_http_port = listen_directives['http'].port

        # See if we need to override the endpoint data
        endpoint_cfg = self.Config.get('Endpoint', None)
        if endpoint_cfg is not None:
            if 'Host' in endpoint_cfg:
                self._endpoint_host = endpoint_cfg['Host']
            if 'Port' in endpoint_cfg:
                self._endpoint_port = int(endpoint_cfg['Port'])
            if 'HttpPort' in endpoint_cfg:
                self._endpoint_http_port = int(endpoint_cfg['HttpPort'])

        # Finally, if the endpoint host is 'localhost', we need to convert it
        # because to another host, obviously 'localhost' won't mean "us"
        if self._endpoint_host == 'localhost':
            self._endpoint_host = socket.gethostbyname(self._endpoint_host)

        self.profile = self.Config.get('Profile', False)

        if self.profile:
            self.pr = cProfile.Profile()
            self.pr.enable()

        self.windows_service = windows_service

        # flag to indicate that a topology update is in progress
        self._topology_update_in_progress = False
        self.delaystart = self.Config['DelayStart']

        # set up signal handlers for shutdown
        if not windows_service:
            signal.signal(signal.SIGTERM, self.handle_shutdown_signal)
            signal.signal(signal.SIGINT, self.handle_shutdown_signal)

        # ---------- Initialize the configuration ----------
        self.initialize_common_configuration()
        self.initialize_ledger_specific_configuration()

        # ---------- Initialize the NodeMap ----------
        self.initialize_node_map()

        # ---------- Initialize the Ledger ----------
        self.initialize_ledger_object()

        self.web_thread_pool = ThreadPool(0, 8, "WebThreadPool")

    def handle_shutdown_signal(self, signum, frame):
        logger.warn('received shutdown signal')
        self.shutdown()

    def shutdown(self):
        """
        Shutdown the validator. There are several things that need to happen
        on shutdown: 1) disconnect this node from the network, 2) close all the
        databases, and 3) shutdown twisted. We need time for each to finish.
        """
        self.status = 'stopping'
        if self.profile:
            self.pr.create_stats()
            loc = os.path.join(self.Config.get('DataDirectory', '/tmp'),
                               '{0}.cprofile'.format(
                                   self.Config.get('NodeName',
                                                   str(os.getpid()))))
            self.pr.dump_stats(loc)

        # send the transaction to remove this node from the endpoint
        # registry (or send it to the web server)
#.........这里部分代码省略.........
开发者ID:yy860179277,项目名称:sawtooth-validator,代码行数:103,代码来源:validator.py

示例11: pylabsTaskletRunner

# 需要导入模块: from twisted.python.threadpool import ThreadPool [as 别名]
# 或者: from twisted.python.threadpool.ThreadPool import stop [as 别名]
class pylabsTaskletRunner(TaskletRunner):
    def __init__(self, engine, threadpoolsize=10):
        self.engine = engine
        # Job queue
        self._queue = Queue.Queue()
        # Threadpool
        self._runners = list()
        self._threadpool = None

        reactor.addSystemEventTrigger('after', 'startup', self.start,
                                      threadpoolsize)
        reactor.addSystemEventTrigger('before', 'shutdown',
                                      self.shutdown)

    def start(self, threadpoolsize):
        self._threadpool = ThreadPool(minthreads=threadpoolsize,
                                      maxthreads=threadpoolsize + 1)

        # Set up threadpool
        q.logger.log('[PMTASKLETS] Constructing taskletserver threadpool', 6)
        self._threadpool.start()
        for i in xrange(threadpoolsize):
            runner = TaskletRunnerThread(self._queue)
            self._runners.append(runner)
            self._threadpool.callInThread(runner.run)

        self._running = True


    def queue(self, params, author=None, name=None, tags=None, priority=-1,
              logname=None):
        author = author or '*'
        name = name or '*'
        tags = tags or list()
        priority = priority if priority > -1 else -1

        q.logger.log('[PMTASKLETS] Queue: params=%s, author=%s, name=%s, '
                     'tags=%s, priority=%d' % \
                     (params, author, name, tags, priority), 4)

        # Wrap the tasklet executor methods so the appname (for logging) is set
        # correctly
        def logwrapper(func):
            @functools.wraps(func)
            def _wrapped(*args, **kwargs):
                import pylabs

                oldappname = pylabs.q.application.appname
                if logname:
                    pylabs.q.application.appname = \
                            'applicationserver:pmtasklets:%s' % logname
                else:
                    pylabs.q.application.appname = \
                            'applicationserver:pmtasklets'

                try:
                    ret = func(*args, **kwargs)
                finally:
                    pylabs.q.application.appname = oldappname

                return ret

            return _wrapped

        execute_args = {
            'author': author,
            'name': name,
            'tags': tags,
            'priority': priority,
            'params': params,
            'wrapper': logwrapper,
        }

        #Append list of tasklet methods to run to the queue
        self._queue.put((self.engine, execute_args, ))

    def shutdown(self):
        q.logger.log('Shutting down tasklet runner', 5)
        self._running = False

        #Tell all threads to stop running
        for runner in self._runners:
            runner.keep_running = False

        self._threadpool.stop()

    @classmethod
    def install(cls):
        log.msg('Installing pylabs tasklet runner')
        import applicationserver

        applicationserver.TaskletRunner = cls
开发者ID:racktivity,项目名称:ext-pylabs-core,代码行数:94,代码来源:pylabs_bindings.py

示例12: test_contemporaneous_requests

# 需要导入模块: from twisted.python.threadpool import ThreadPool [as 别名]
# 或者: from twisted.python.threadpool.ThreadPool import stop [as 别名]
def test_contemporaneous_requests():
    '''
    We're going to create two request-response cycles here:

    Cycle 1 will begin.
    Cycle 2 will begin.
    Cycle 2 will return.
    Cycle 1 will return.

    This way, we can prove that the crosstown_traffic created
    by cycle 1 is not resolved by the return of cycle 2.
    '''
    tp = ThreadPool(maxthreads=20)
    tp.start()

    log.debug("\n\nStarting the two stream stuff.")

    request1 = DummyRequest([b'r1'])
    request1.isSecure = lambda: False
    request1.content = "Nothing really here."
    request1.requestHeaders.addRawHeader('llamas', 'dingo')
    request1.client = IPv4Address("TCP", b"50.0.50.0", 5000)

    hr = HendrixWSGIResource(reactor, tp, wsgi_application)
    yield deferToThreadPool(reactor, tp, hr.render, request1)

    request2 = DummyRequest([b'r2'])
    request2.isSecure = lambda: False
    request2.content = b"Nothing really here."
    request2.requestHeaders.addRawHeader('llamas', 'dingo')
    request2.client = IPv4Address("TCP", b"100.0.50.0", 5000)

    yield deferToThreadPool(reactor, tp, hr.render, request2)

    # def woah_stop(failure):
    #     nameSpace.async_task_was_done.put_nowait(False)
    #     nameSpace.second_cycle_complete.put_nowait(False)
    #     nameSpace.ready_to_proceed_with_second_cycle.put_nowait(False)
    #
    # d1.addErrback(woah_stop)
    # d2.addErrback(woah_stop)

    # combo_deferred = gatherResults([d1, d2])
    # yield d1
    # yield d2
    # combo_deferred = DeferredList([d1, d2])

    def wait_for_queue_resolution():
        nameSpace.async_task_was_done.get(True, 3)

    # combo_deferred.addCallback(
    #     lambda _:
    # )
    #
    yield deferToThreadPool(reactor, tp, wait_for_queue_resolution)

    # combo_deferred.addCallback(
    #     lambda _:
    # )
    assert nameSpace.async_task_was_run
    tp.stop()
开发者ID:hendrix,项目名称:hendrix,代码行数:63,代码来源:test_crosstown_traffic.py

示例13: UpdateTest

# 需要导入模块: from twisted.python.threadpool import ThreadPool [as 别名]
# 或者: from twisted.python.threadpool.ThreadPool import stop [as 别名]
class UpdateTest(unittest.TestCase):
    def setUp(self):
        self.db = MockStore()
        GSM.registerUtility(MockZStorm(self.db))

        self.tp = ThreadPool(0, 2)
        self.sm = MockServerManager(reactor, SERVERS)
        self.updater = Updater(Transactor(self.tp), self.sm)
        self.tp.start()

    def tearDown(self):
        self.tp.stop()

    def _H(self, **k):
        h = Home()
        for k, v in k.iteritems():
            setattr(h, k, v)
        self.db.add(h)
        return h

    def _S(self, **k):
        h = HomeState()
        for k, v in k.iteritems():
            setattr(h, k, v)
        self.db.add(h)
        return h

    @defer.inlineCallbacks
    def test_creation(self):
        home = self._H(
            server_name = "foo",
            path = "/test",
        )

        fooserv = yield self.sm.getServer("foo")

        self.assertNotIn((home.id, "foo"), self.db.objects[HomeState])
        self.assertNotIn("/data/homes/test", fooserv.known_paths)

        done = yield self.updater.updateOne(home, [])

        self.assertIn((home.id, "foo"), self.db.objects[HomeState])
        self.assertIn("/data/homes/test", self.sm.servers["foo"].known_paths)

    @defer.inlineCallbacks
    def test_move(self):
        home = self._H(
            server_name = "foo",
            path = "/test",
        )

        status = self._S(
            id = home.id,
            server_name = "foo",
            path = "/old_dir",
            status = HomeState.ACTIVE,
        )

        fooserv = yield self.sm.getServer("foo")
        fooserv.known_paths.add("/data/homes/old_dir")

        done = yield self.updater.updateOne(home, [status])

        self.assertIn((home.id, "foo"), self.db.objects[HomeState])
        status = self.db.objects[HomeState][(home.id, "foo")]
        self.assertEquals(status.path, home.path)

        self.assertIn("/data/homes/test", self.sm.servers["foo"].known_paths)
        self.assertNotIn("/data/homes/old_dir", self.sm.servers["foo"].known_paths)


    @defer.inlineCallbacks
    def test_archive(self):
        home = self._H(
            server_name = "foo",
            path = None,
        )

        status = self._S(
            id = home.id,
            server_name = "foo",
            path = "/foo",
            status = HomeState.ACTIVE,
        )

        fooserv = yield self.sm.getServer("foo")
        fooserv.known_paths.add("/data/homes/foo")

        self.assertNotIn("/data/archive/foo", fooserv.known_paths)

        done = yield self.updater.updateOne(home, [status])

        status = self.db.objects[HomeState][(home.id, "foo")]
        self.assertEquals(status.status, HomeState.ARCHIVED)

        self.assertIn("/data/archive/foo", fooserv.known_paths)
        self.assertNotIn("/data/homes/foo", fooserv.known_paths)

    @defer.inlineCallbacks
    def test_sync(self):
#.........这里部分代码省略.........
开发者ID:veloutin,项目名称:tilde,代码行数:103,代码来源:test_core.py

示例14: ServerTwisted

# 需要导入模块: from twisted.python.threadpool import ThreadPool [as 别名]
# 或者: from twisted.python.threadpool.ThreadPool import stop [as 别名]
class ServerTwisted(AbstractServer):
    """
"ServerTwisted" is responsible to start the HTTP Twisted server.

:author:     direct Netware Group et al.
:copyright:  (C) direct Netware Group - All rights reserved
:package:    pas.http
:subpackage: core
:since:      v1.0.0
:license:    https://www.direct-netware.de/redirect?licenses;mpl2
             Mozilla Public License, v. 2.0
    """

    def __init__(self):
        """
Constructor __init__(ServerTwisted)

:since: v1.0.0
        """

        AbstractServer.__init__(self)

        self.log_observer = None
        """
@TODO
        """
        self.reactor = None
        """
Twisted reactor instance
        """
        self.thread_pool = None
        """
@TODO
        """

        log_handler = NamedLoader.get_singleton("dNG.data.logging.LogHandler", False)

        if (log_handler is not None):
            log_handler.add_logger("twisted")

            self.log_observer = log.PythonLoggingObserver("twisted")
            self.log_observer.start()

            log.startLoggingWithObserver(self.log_observer.emit, setStdout = False)
        #
    #

    def _configure(self):
        """
Configures the server

:since: v1.0.0
        """

        listener_host = Settings.get("pas_http_twisted_server_host", self.socket_hostname)
        self.port = int(Settings.get("pas_http_twisted_server_port", 8080))

        self.reactor = reactor
        self.reactor.addSystemEventTrigger('before', 'shutdown', self.stop)

        server_description = "tcp:{0:d}".format(self.port)

        if (listener_host == ""): self.host = Settings.get("pas_http_server_preferred_hostname", self.socket_hostname)
        else:
            self.host = listener_host
            server_description += ":interface={0}".format(self.host)
        #

        self.thread_pool = ThreadPool()
        self.thread_pool.start()

        if (self._log_handler is not None): self._log_handler.info("pas.http.core Twisted server starts at '{0}:{1:d}'", listener_host, self.port, context = "pas_http_core")

        server = serverFromString(self.reactor, server_description)
        server.listen(Site(WSGIResource(reactor, self.thread_pool, HttpWsgi1Request)))

        """
Configure common paths and settings
        """

        AbstractServer._configure(self)
    #

    def run(self):
        """
Runs the server

:since: v1.0.0
        """

        self.reactor.startRunning(installSignalHandlers = False)
        with ExceptionLogTrap("pas_http_core"): self.reactor.mainLoop()
    #

    def stop(self, params = None, last_return = None):
        """
Stop the server

:param params: Parameter specified
:param last_return: The return value from the last hook called.
#.........这里部分代码省略.........
开发者ID:dNG-git,项目名称:pas_http_core,代码行数:103,代码来源:server_twisted.py

示例15: DbPool

# 需要导入模块: from twisted.python.threadpool import ThreadPool [as 别名]
# 或者: from twisted.python.threadpool.ThreadPool import stop [as 别名]
class DbPool(object,service.Service):
	"""\
	Manage a pool of database connections.

	TODO: shrink the pool.
	TODO: issue periodic keepalive requests.
	"""
	timeout = 70 # one minute plus
	implements(service.IService)

	def __init__(self,*a,**k):
		"""\
		Create a pool of database connections, for processing (a sequence of)
		SQL commands in the background.
		"""
		k['_single_thread'] = True

		self.db = []
		self.args = a
		self.kwargs = k
		self.lock = Lock()
		self.cleaner = None
		self._tb = {}
		self.stopping = False
		self.threads = ThreadPool(minthreads=2, maxthreads=100, name="Database")
		self.threads.start()
		#reactor.addSystemEventTrigger('before', 'shutdown', self.stop)
		reactor.addSystemEventTrigger('after', 'shutdown', self._dump)
		reactor.addSystemEventTrigger('after', 'shutdown', self.stop2)

	def stop2(self):
		if self.db is not None:
			for db in self.db:
				db[0].close("AfterShutdown Service")
		self.threads.stop()

	def stop(self):
		self.stopping = True

	def _get_db(self,tid=None):
		if self.db:
			r = self.db.pop()[0]
			s="OLD"
		else:
			r = _DbThread(self)
			s="NEW"

		if tid:
			debug(s, r.tid,tid)
			r.tid=tid
		else:
			debug(s, r.tid)

		return r

	def _put_db(self,db):
		if self.db is None or self.stopping:
			db.close("Shutdown")
			return db.done
		if db.q is None:
			raise RuntimeError("Queueing closed DB handle")
		for d in self.db:
			if db is d[0]:
				raise RuntimeError("DoubleQueued")
		db.count = 0
		try:
			t = time()+self.timeout
			self.db.append((db,t))
			if self.cleaner is None:
				self.cleaner = reactor.callLater(self.timeout,self._clean)
		except Exception:
			print_exc()
		else:
			debug("BACK",db.tid)
	
	def _clean(self):
		self.cleaner = None
		t = time()
		while self.db and self.db[0][1] <= t:
			db = self.db.pop(0)[0]
			db.close("Timeout")
		if self.db:
			self.cleaner = reactor.callLater(self.db[0][1]-t,self._clean)
	def __del__(self):
		if self.cleaner:
			reactor.cancelCallLater(self.cleaner)
			self.cleaner = None
		while self.db:
			db = self.db.pop(0)[0]
			db.close("Nonref Parent")

	def stopService(self):
		super(DbPool,self).stopService()
		if self.cleaner:
			self.cleaner.cancel()
			self.cleaner = None
		dbl = self.db
		self.db = None
		dl = []
		for db in dbl:
#.........这里部分代码省略.........
开发者ID:smurfix,项目名称:sqlmix,代码行数:103,代码来源:twisted.py


注:本文中的twisted.python.threadpool.ThreadPool.stop方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。