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


Python Thread.join方法代码示例

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


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

示例1: test_cancel_workflow_with_activity_cascade

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import join [as 别名]
    def test_cancel_workflow_with_activity_cascade(self):
        class SelfCancellingWorkflowWithCascade(WorkflowDefinition):
            def __init__(self, workflow_execution):
                super(SelfCancellingWorkflowWithCascade, self).__init__(workflow_execution)
                self.activities_client = BunchOfActivities()

            @execute(version='1.1', execution_start_to_close_timeout=60)
            def execute(self):
                self.activities_client.heartbeating_activity(5)
                yield workflow_time.sleep(1)
                self.cancel()
                return_(True)

        wf = SelfCancellingWorkflowWithCascade
        wf_worker, act_worker = self.get_workers(wf)
        self.start_workflow(wf)

        act_worker_thread = Thread(target=act_worker.run_once)
        act_worker_thread.start()
        wf_worker.run_once()  # start activity
        wf_worker.run_once()  # cancel workflow and the heartbeat activity
        act_worker_thread.join()
        time.sleep(1)

        hist = self.get_workflow_execution_history()
        self.assertEqual(hist[-1]['eventType'], 'WorkflowExecutionCanceled')
        self.assertEqual(hist[-2]['eventType'], 'ActivityTaskCancelRequested')
        # hist differs depending on whether the heartbeat activity started or not
        self.assertEqual(len(hist), 13)
开发者ID:notthatbreezy,项目名称:botoflow,代码行数:31,代码来源:test_cancellation.py

示例2: run

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import join [as 别名]
def run(**kwargs):

    thread_queue = []
    for provider in list_providers("openstack"):
        mgmt_sys = cfme_data['management_systems'][provider]
        rhos_credentials = credentials[mgmt_sys['credentials']]
        default_host_creds = credentials['host_default']

        username = rhos_credentials['username']
        password = rhos_credentials['password']
        auth_url = mgmt_sys['auth_url']
        rhosip = mgmt_sys['ipaddress']
        sshname = default_host_creds['username']
        sshpass = default_host_creds['password']
        if not net.is_pingable(rhosip):
            continue
        if not net.net_check(ports.SSH, rhosip):
            print("SSH connection to {}:{} failed, port unavailable".format(
                provider, ports.SSH))
            continue
        thread = Thread(target=upload_template,
                        args=(rhosip, sshname, sshpass, username, password, auth_url, provider,
                              kwargs.get('image_url'), kwargs.get('template_name')))
        thread.daemon = True
        thread_queue.append(thread)
        thread.start()

    for thread in thread_queue:
        thread.join()
开发者ID:prachiyadav,项目名称:cfme_tests,代码行数:31,代码来源:template_upload_rhos.py

示例3: TestStatsdLoggingDelegation

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import join [as 别名]
class TestStatsdLoggingDelegation(unittest.TestCase):
    def setUp(self):
        self.port = 9177
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.bind(('localhost', self.port))
        self.queue = Queue()
        self.reader_thread = Thread(target=self.statsd_reader)
        self.reader_thread.setDaemon(1)
        self.reader_thread.start()

    def tearDown(self):
        # The "no-op when disabled" test doesn't set up a real logger, so
        # create one here so we can tell the reader thread to stop.
        if not getattr(self, 'logger', None):
            self.logger = utils.get_logger({
                'log_statsd_host': 'localhost',
                'log_statsd_port': str(self.port),
            }, 'some-name')
        self.logger.increment('STOP')
        self.reader_thread.join(timeout=4)
        self.sock.close()
        del self.logger
        time.sleep(0.15)  # avoid occasional "Address already in use"?

    def statsd_reader(self):
        while True:
            try:
                payload = self.sock.recv(4096)
                if payload and 'STOP' in payload:
                    return 42
                self.queue.put(payload)
            except Exception, e:
                sys.stderr.write('statsd_reader thread: %r' % (e,))
                break
开发者ID:AsylumCorp,项目名称:swift,代码行数:36,代码来源:test_utils.py

示例4: main

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import join [as 别名]
 def main(self):
     global QUEUE
     QUEUE = TaskQueue(self.config)
     
     indexers = self.buildIndexers()
            
     for indexer in indexers: 
         QUEUE.put(indexer)
     
     #start stat printing
     if self.statManager != None:
         timer = Timer()
         timer.scheduleAtFixedRate(StatLoggerTask(self.statManager, indexers), 0, self.config.statLoggingFrequency*60*1000)
     
     #start worker threads        
     workers = []
     for i in range(self.config.numThreads):
         t = Thread (target=ISWorker(self.config, self.statManager))
         workers.append(t)
         t.setDaemon(1)
         t.start()
             
     for t in workers:
         t.join()
         
     log('Done!')
开发者ID:piyush76,项目名称:EMS,代码行数:28,代码来源:isctrl.py

示例5: test_request_retries_configurable

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import join [as 别名]
    def test_request_retries_configurable(self):
        # We guess at some ports that will be unused by Riak or
        # anything else.
        client = self.create_client(http_port=DUMMY_HTTP_PORT,
                                    pb_port=DUMMY_PB_PORT)

        # Change the retry count
        client.retries = 10
        self.assertEqual(10, client.retries)

        # The retry count should be a thread local
        retries = Queue()

        def _target():
            retries.put(client.retries)
            retries.join()

        th = Thread(target=_target)
        th.start()
        self.assertEqual(3, retries.get(block=True))
        retries.task_done()
        th.join()

        # Modify the retries in a with statement
        with client.retry_count(5):
            self.assertEqual(5, client.retries)
            self.assertRaises(IOError, client.ping)
开发者ID:GabrielNicolasAvellaneda,项目名称:riak-python-client,代码行数:29,代码来源:test_all.py

示例6: __init__

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import join [as 别名]
class AlarmExecutor:
    def __init__(self):
        self.queue = JoinableQueue(10)
        self.running = False
        self.t = Thread(target=self._run, name="AlarmExecutor")

    def _run(self):
        while self.running:
            try:
                alarm = self.queue.get(block=True, timeout=1)
                alarm.execute() 
                logging.debug("Alarm executed")
                self.queue.task_done()       
            except Queue.Empty:
                continue
            
    def start(self):
        logging.debug("Starting alarm executor")
        self.running = True
        self.t.start()

    def stop(self):
        if self.running:
            logging.debug("Stoppping alarm executor")
            self.running = False
            self.t.join()
        else:
            logging.debug("Attempted to stop alarm executor when it is not running")
开发者ID:RaveGun,项目名称:redeem,代码行数:30,代码来源:Alarm.py

示例7: PseudoSocketServer

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import join [as 别名]
class PseudoSocketServer(Server, PseudoSide):

    def __init__(self, file_path):
        if os.path.exists(file_path):
            os.remove(file_path)
        self._file_path = file_path
        self._listening = False
        self._async_listener = Thread(target=self._listen_task)

    def _listen_task(self):
        print("[server] Connects by {!s}".format(self._file_path))
        open(self._file_path, 'a').close()
        self._listening = True
        while self._listening:
            received = self.read_and_remove(self._file_path, "server")
            if received:
                print("[server] Server got message")
                answer = self.HELLO_FORMAT.format(received)
                self.append_to_file(self._file_path, answer, "server")
            time.sleep(0.25)

    def listen(self):
        self._async_listener.start()

    def close(self):
        print("[server] Shutdowns socket")
        self._listening = False

        if self._async_listener.is_alive():
            print("[server] Joins background task")
            self._async_listener.join()
开发者ID:BCNDojos,项目名称:pyDojos,代码行数:33,代码来源:pseudosocketserver.py

示例8: runHook

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import join [as 别名]
def runHook(hookFunc, *args):
    class Hook(object):
        def __init__(self):
            self._stop = True

        def ended(self):
            self._stop = False

        def stop(self):
            return self._stop


    hookName = hookFunc.__name__

    # Don't run hooks for action unitTests.
    if hookName == 'preHook':
        if args[0] == 'unitTests':
            return False

    hook = Hook()
    args += (hook,)

    thread = Thread(name=hookName, target=hookFunc, args=args, daemon=True)
    thread.start()
    thread.join(10) # TODO: get timeout from rascal.

    return hook.stop()
开发者ID:nicolas33,项目名称:imapfw,代码行数:29,代码来源:toolkit.py

示例9: test_term_thread

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import join [as 别名]
    def test_term_thread(self):
        """ctx.term should not crash active threads (#139)"""
        ctx = self.Context()
        evt = Event()
        evt.clear()

        def block():
            s = ctx.socket(zmq.REP)
            s.bind_to_random_port('tcp://127.0.0.1')
            evt.set()
            try:
                s.recv()
            except zmq.ZMQError as e:
                self.assertEqual(e.errno, zmq.ETERM)
                return
            finally:
                s.close()
            self.fail("recv should have been interrupted with ETERM")
        t = Thread(target=block)
        t.start()
        
        evt.wait(1)
        self.assertTrue(evt.is_set(), "sync event never fired")
        time.sleep(0.01)
        ctx.term()
        t.join(timeout=1)
        self.assertFalse(t.is_alive(), "term should have interrupted s.recv()")
开发者ID:JathavanSriram,项目名称:pyzmq,代码行数:29,代码来源:test_context.py

示例10: test_bad_negotiation

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import join [as 别名]
	def test_bad_negotiation(self):
		portnum = find_available_port()
		servsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		servsock.bind(('localhost', portnum))
		pc = c3.Connection(
			SocketFactory(
				(socket.AF_INET, socket.SOCK_STREAM),
				('localhost', portnum)
			),
			{}
		)
		exc = None
		servsock.listen(1)
		def client_thread():
			pc.connect()
		client = Thread(target = client_thread)
		try:
			client.start()
			c, addr = servsock.accept()
			try:
				c.recv(1024)
			finally:
				c.close()
			time.sleep(0.25)
			client.join()
			servsock.close()
			self.assertEqual(pc.xact.fatal, True)
			self.assertEqual(pc.xact.__class__, x3.Negotiation)
			self.assertEqual(pc.xact.error_message.__class__, e3.ClientError)
			self.assertEqual(pc.xact.error_message[b'C'], '08006')
		finally:
			servsock.close()
			if pc.socket is not None:
				pc.socket.close()
开发者ID:AtomLaw,项目名称:Superdesk,代码行数:36,代码来源:test_protocol.py

示例11: api_call_threaded

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import join [as 别名]
 def api_call_threaded(self, requests):
     """
     Interface for a multi-threaded API call, to speed up the request/response cycle when
     calling multiple endpoints when rendering a template.
     """
     
     # Threads / responses
     threads   = []
     
     # Process each request
     for key,attr in requests.iteritems():
     
         # Get any request data
         data   = None if (len(attr) == 2) else attr[2]
     
         # Create the thread, append, and start
         thread = Thread(target=self._api_call_threaded_worker, args=[key, attr[0], attr[1], data])
         threads.append(thread)
         thread.start()
         
     # Wait for the API calls to complete
     for thread in threads:
         thread.join()
     self.log.info('API_CALL_THREADED: %s' % str(self._response))
         
     # Return the response object
     return self._response
开发者ID:djtaylor,项目名称:lense-portal,代码行数:29,代码来源:template.py

示例12: test_SSL_failure

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import join [as 别名]
	def test_SSL_failure(self):
		portnum = find_available_port()
		servsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		with servsock:
			servsock.bind(('localhost', portnum))
			pc = c3.Connection(
				SocketFactory(
					(socket.AF_INET, socket.SOCK_STREAM),
					('localhost', portnum)
				),
				{}
			)
			exc = None
			servsock.listen(1)
			def client_thread():
				pc.connect(ssl = True)
			client = Thread(target = client_thread)
			try:
				client.start()
				c, addr = servsock.accept()
				with c:
					c.send(b'S')
					c.sendall(b'0000000000000000000000')
					c.recv(1024)
					c.close()
				client.join()
			finally:
				if pc.socket is not None:
					pc.socket.close()

		self.assertEqual(pc.xact.fatal, True)
		self.assertEqual(pc.xact.__class__, x3.Negotiation)
		self.assertEqual(pc.xact.error_message.__class__, e3.ClientError)
		self.assertTrue(hasattr(pc.xact, 'exception'))
开发者ID:AtomLaw,项目名称:Superdesk,代码行数:36,代码来源:test_protocol.py

示例13: power_on

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import join [as 别名]
def power_on(vm):
	"""Powers on virtual machine and answers any input
	   messages that might appear. """
	# vm.powerOn()
	power_thd = Thread(target = vm.powerOn)
	power_thd.start()
	power_thd.join()
开发者ID:unbaiat,项目名称:vmgen,代码行数:9,代码来源:vmgControlVmware.py

示例14: handle_noargs

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import join [as 别名]
    def handle_noargs(self, **options):
        verbose = int(options['verbosity'])
        send_all = True

        if verbose:
            print 'Starting sending newsletters...'

        activate(settings.LANGUAGE_CODE)

        senders = SMTPServer.objects.all()
        workers = []

        for sender in senders:
            worker = SMTPMailer(sender, verbose=verbose)
            thread = Thread(target=functools.partial(worker.run, send_all), name=sender.name)
            workers.append((worker, thread))

        handler = term_handler(workers)
        for s in [signal.SIGTERM, signal.SIGINT]:
            signal.signal(s, handler)

        # first close current connection
        signals.request_finished.send(sender=self.__class__)

        for worker, thread in workers:
            thread.start()

        signal.pause()  # wait for sigterm

        for worker, thread in workers:
            if thread.is_alive():
                thread.join()

        sys.exit(0)
开发者ID:nephila,项目名称:django-maja-newsletter,代码行数:36,代码来源:send_newsletter_continuous.py

示例15: test_get_loaders_multithreads

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import join [as 别名]
    def test_get_loaders_multithreads(self):
        """Test case that ensures loaders are loaded by one single thread even if multiple threads request
        loaders list."""

        self._settings_facade.get = Mock(
            return_value=[
                "fantastico.routing_engine.tests.test_router.TestLoader",
                "fantastico.routing_engine.tests.test_router.TestLoader2",
                "fantastico.routing_engine.tests.test_router.TestLoader3",
            ]
        )

        threads = []

        def get_loaders_async(router):
            router.get_loaders()

        for i in range(0, 10):
            thread = Thread(target=get_loaders_async, name="GetLoadersThread-%s" % i, kwargs={"router": self._router})
            threads.append(thread)
            thread.start()

        for thread in threads:
            thread.join(100)

        loaders = self._router.get_loaders()

        self.assertIsNotNone(loaders)
        self.assertEqual(3, len(loaders))
        self.assertIsInstance(loaders[0], TestLoader)
        self.assertIsInstance(loaders[1], TestLoader2)
        self.assertIsInstance(loaders[2], TestLoader3)
开发者ID:rcosnita,项目名称:fantastico,代码行数:34,代码来源:test_router.py


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