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


Python threading.active_count方法代码示例

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


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

示例1: zmirror_status

# 需要导入模块: import threading [as 别名]
# 或者: from threading import active_count [as 别名]
def zmirror_status():
    """返回服务器的一些状态信息"""
    if request.remote_addr and request.remote_addr != '127.0.0.1':
        return generate_simple_resp_page(b'Only 127.0.0.1 are allowed', 403)
    output = ""
    output += strx('extract_real_url_from_embedded_url', extract_real_url_from_embedded_url.cache_info())
    output += strx('\nis_content_type_streamed', is_mime_streamed.cache_info())
    output += strx('\nembed_real_url_to_embedded_url', embed_real_url_to_embedded_url.cache_info())
    output += strx('\ncheck_global_ua_pass', check_global_ua_pass.cache_info())
    output += strx('\nextract_mime_from_content_type', extract_mime_from_content_type.cache_info())
    output += strx('\nis_content_type_using_cdn', is_content_type_using_cdn.cache_info())
    output += strx('\nis_ua_in_whitelist', is_content_type_using_cdn.cache_info())
    output += strx('\nis_mime_represents_text', is_mime_represents_text.cache_info())
    output += strx('\nis_domain_match_glob_whitelist', is_domain_match_glob_whitelist.cache_info())
    output += strx('\nverify_ip_hash_cookie', verify_ip_hash_cookie.cache_info())
    output += strx('\nis_denied_because_of_spider', is_denied_because_of_spider.cache_info())
    output += strx('\nis_ip_not_in_allow_range', is_ip_not_in_allow_range.cache_info())
    output += strx('\n\ncurrent_threads_number', threading.active_count())
    # output += strx('\nclient_requests_text_rewrite', client_requests_text_rewrite.cache_info())
    # output += strx('\nextract_url_path_and_query', extract_url_path_and_query.cache_info())

    output += strx('\n----------------\n')
    output += strx('\ndomain_alias_to_target_set', domain_alias_to_target_set)

    return "<pre>" + output + "</pre>\n" 
开发者ID:aploium,项目名称:zmirror,代码行数:27,代码来源:zmirror.py

示例2: enable_async

# 需要导入模块: import threading [as 别名]
# 或者: from threading import active_count [as 别名]
def enable_async():
    global enabled

    if enabled:
        return enabled

    if threading.active_count() > 3:
        # This number used to be 1, but a gevent patch or something else changed this so it starts with 3 threads
        logger.warning('{} threads already running. gvent monkey patching disabled...'.format(threading.active_count()))
        enabled = False

    else:
        logger.debug('Monkey patching using gevent')
        gevent.monkey.patch_all()
        enabled = True

    return enabled 
开发者ID:mitre,项目名称:cascade-server,代码行数:19,代码来源:async.py

示例3: test_dummy_thread_after_fork

# 需要导入模块: import threading [as 别名]
# 或者: from threading import active_count [as 别名]
def test_dummy_thread_after_fork(self):
        # Issue #14308: a dummy thread in the active list doesn't mess up
        # the after-fork mechanism.
        code = """if 1:
            import thread, threading, os, time

            def background_thread(evt):
                # Creates and registers the _DummyThread instance
                threading.current_thread()
                evt.set()
                time.sleep(10)

            evt = threading.Event()
            thread.start_new_thread(background_thread, (evt,))
            evt.wait()
            assert threading.active_count() == 2, threading.active_count()
            if os.fork() == 0:
                assert threading.active_count() == 1, threading.active_count()
                os._exit(0)
            else:
                os.wait()
        """
        _, out, err = assert_python_ok("-c", code)
        self.assertEqual(out, '')
        self.assertEqual(err, '') 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:27,代码来源:test_threading.py

示例4: test_start_stop

# 需要导入模块: import threading [as 别名]
# 或者: from threading import active_count [as 别名]
def test_start_stop(self, proc_pool):
        """Test basic start/stop of ProcessPool."""
        # This testcase is known to fail on Windows - mark as xfail until we
        # can fix it up.
        if platform.system() == "Windows":
            pytest.xfail("ProcPool start/stop is unstable on Windows")

        current_proc = psutil.Process()
        start_children = current_proc.children()
        start_thread_count = threading.active_count()

        # Iterate 5 times to increase the chance of hitting a race condition.
        for _ in range(5):
            with proc_pool:
                assert proc_pool.status.tag == proc_pool.status.STARTED
                assert len(current_proc.children()) == len(start_children) + 2

            assert proc_pool.status.tag == proc_pool.status.STOPPED
            assert len(current_proc.children()) == len(start_children) 
开发者ID:Morgan-Stanley,项目名称:testplan,代码行数:21,代码来源:test_process_worker.py

示例5: output

# 需要导入模块: import threading [as 别名]
# 或者: from threading import active_count [as 别名]
def output(self):
        
        with open(RunParameters.OUTPUT_FILE, "a") as csv_file:
            writer = csv.writer(csv_file, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
            while (time.time() - self.start_time) < self.time_limit:
                
                #computing snapshots
                num_snapshots = 0
                for key in self.state_graph.states:
                    if self.state_graph.states[key].solid:
                        num_snapshots = num_snapshots+1
                
                #read coverage
                coverage_manager.pull_coverage_files("temp")
                coverage_manager.compute_current_coverage()             # output in coverage.txt
                current_coverage = coverage_manager.read_current_coverage()

                # write files
                writer.writerow([str(int(time.time()-self.start_time)), str(len(self.state_graph.states)),str(num_snapshots), str(self.num_restore), str(current_coverage)])
                time.sleep(120)
                
                print "current threads:  " + str(threading.active_count())


        csv_file.close() 
开发者ID:DroidTest,项目名称:TimeMachine,代码行数:27,代码来源:executor.py

示例6: __init__

# 需要导入模块: import threading [as 别名]
# 或者: from threading import active_count [as 别名]
def __init__(self, queue_name, fucntion_name, params):
        self.queue_name = queue_name
        self.function = fucntion_name
        publish_time = _get_publish_time(params)
        if publish_time:
            self.publish_time_str = time_util.DatetimeConverter(publish_time).datetime_str
        function_params = _delete_keys_and_return_new_dict(params, )
        self.params = function_params
        self.params_str = json.dumps(function_params, ensure_ascii=False)
        self.result = ''
        self.run_times = 0
        self.exception = ''
        self.time_start = time.time()
        self.time_cost = None
        self.success = False
        self.current_thread = ConsumersManager.get_concurrent_info()
        self.total_thread = threading.active_count()
        self.set_log_level(20) 
开发者ID:ydf0509,项目名称:distributed_framework,代码行数:20,代码来源:base_consumer.py

示例7: show_current_threads_num

# 需要导入模块: import threading [as 别名]
# 或者: from threading import active_count [as 别名]
def show_current_threads_num(sleep_time=60, process_name='', block=False):
    process_name = sys.argv[0] if process_name == '' else process_name

    def _show_current_threads_num():
        while True:
            # logger_show_current_threads_num.info(f'{process_name} 进程 的 并发数量是 -->  {threading.active_count()}')
            nb_print(f'{process_name} 进程 的 线程数量是 -->  {threading.active_count()}')
            time.sleep(sleep_time)

    if process_name not in process_name_set:
        if block:
            _show_current_threads_num()
        else:
            t = threading.Thread(target=_show_current_threads_num, daemon=True)
            t.start()
        process_name_set.add(process_name) 
开发者ID:ydf0509,项目名称:distributed_framework,代码行数:18,代码来源:custom_threadpool_executor.py

示例8: test_dummy_thread_after_fork

# 需要导入模块: import threading [as 别名]
# 或者: from threading import active_count [as 别名]
def test_dummy_thread_after_fork(self):
        # Issue #14308: a dummy thread in the active list doesn't mess up
        # the after-fork mechanism.
        code = """if 1:
            import _thread, threading, os, time

            def background_thread(evt):
                # Creates and registers the _DummyThread instance
                threading.current_thread()
                evt.set()
                time.sleep(10)

            evt = threading.Event()
            _thread.start_new_thread(background_thread, (evt,))
            evt.wait()
            assert threading.active_count() == 2, threading.active_count()
            if os.fork() == 0:
                assert threading.active_count() == 1, threading.active_count()
                os._exit(0)
            else:
                os.wait()
        """
        _, out, err = assert_python_ok("-c", code)
        self.assertEqual(out, b'')
        self.assertEqual(err, b'') 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:27,代码来源:test_threading.py

示例9: test_safe_terminate

# 需要导入模块: import threading [as 别名]
# 或者: from threading import active_count [as 别名]
def test_safe_terminate(execmodel):
    if execmodel.backend != "threading":
        pytest.xfail(
            "execution model %r does not support task count" % execmodel.backend
        )
    import threading

    active = threading.active_count()
    l = []

    def term():
        sleep(3)

    def kill():
        l.append(1)

    safe_terminate(execmodel, 1, [(term, kill)] * 10)
    assert len(l) == 10
    sleep(0.1)
    gc.collect()
    assert execmodel.active_count() == active 
开发者ID:pytest-dev,项目名称:execnet,代码行数:23,代码来源:test_multi.py

示例10: test_safe_terminate2

# 需要导入模块: import threading [as 别名]
# 或者: from threading import active_count [as 别名]
def test_safe_terminate2(execmodel):
    if execmodel.backend != "threading":
        pytest.xfail(
            "execution model %r does not support task count" % execmodel.backend
        )
    import threading

    active = threading.active_count()
    l = []

    def term():
        return

    def kill():
        l.append(1)

    safe_terminate(execmodel, 3, [(term, kill)] * 10)
    assert len(l) == 0
    sleep(0.1)
    gc.collect()
    assert threading.active_count() == active 
开发者ID:pytest-dev,项目名称:execnet,代码行数:23,代码来源:test_multi.py

示例11: nodeSelected

# 需要导入模块: import threading [as 别名]
# 或者: from threading import active_count [as 别名]
def nodeSelected(self, value):
        try:

            self.validNode = False
            counter = 0
            while(threading.active_count()>2 and counter<100):
                time.sleep(0.01)

            self.resetAll()

            if value>0 and counter<100:
                self.node_name = self.node_list[value-1]
                if "/"+self.node_name+"/specs" in dict(self.node.get_service_names_and_types()):
                    self.validNode = True
                    self.connectToNode()
                else:
                    self.validNode = False
                    print("Not a valid HRIM gripper node")
        except:
            raise 
开发者ID:AcutronicRobotics,项目名称:HRIM,代码行数:22,代码来源:interface.py

示例12: _main

# 需要导入模块: import threading [as 别名]
# 或者: from threading import active_count [as 别名]
def _main(self):
		with open(sys.argv[1]) as f:
			self.total=sum(bl.count("\n") for bl in self.blocks(f))
			print self.total
		t = threading.Thread(target=self.read_url_list)
		t.daemon = True
		t.start()
		time.sleep(5)
		for i in range(0,MAX_THREAD):
			t = threading.Thread(target=self._check)
			t.daemon = True
			t.start()
		while self.url_queue.qsize() !=0:
			sys.stdout.write("Current threads: %d,URLs left: %d,Success:%d                             \r" % (
			threading.active_count(), self.total, self.success), )
			sys.stdout.flush()
			time.sleep(0.3)
		while threading.active_count() > 1:
			sys.stdout.write("Current threads: %d,URLs left: %d,Success:%d                             \r" % (
			threading.active_count(), self.total, self.success), )
			sys.stdout.flush()
			time.sleep(1) 
开发者ID:dc3l1ne,项目名称:Weblogic-Weakpassword-Scnner,代码行数:24,代码来源:spider.py

示例13: start

# 需要导入模块: import threading [as 别名]
# 或者: from threading import active_count [as 别名]
def start(self):
        assert self._job.pending
        # create the listener thread to handle incoming requests
        listener = threading.Thread(
            target=self.listener,
            args=(self._socket, self._job, self._workers),
            kwargs={"shutdown_delay": self.SHUTDOWN_DELAY})
        # launch listener thread and handle thread errors
        for retry in reversed(range(10)):
            try:
                listener.start()
            except threading.ThreadError:
                # thread errors can be due to low system resources while fuzzing
                LOG.warning("ThreadError (listener), threads: %d", threading.active_count())
                if retry < 1:
                    raise
                time.sleep(1)
                continue
            self._listener = listener
            break 
开发者ID:MozillaSecurity,项目名称:grizzly,代码行数:22,代码来源:sapphire_load_manager.py

示例14: launch

# 需要导入模块: import threading [as 别名]
# 或者: from threading import active_count [as 别名]
def launch(cls, listen_sock, job):
        assert job.accepting.is_set()
        conn = None
        try:
            conn, _ = listen_sock.accept()
            conn.settimeout(None)
            # create a worker thread to handle client request
            w_thread = threading.Thread(target=cls.handle_request, args=(conn, job))
            job.accepting.clear()
            w_thread.start()
            return cls(conn, w_thread)
        except (socket.error, socket.timeout):
            if conn is not None:  # pragma: no cover
                conn.close()
        except threading.ThreadError:
            if conn is not None:  # pragma: no cover
                conn.close()
            # reset accepting status
            job.accepting.set()
            LOG.warning("ThreadError (worker), threads: %d", threading.active_count())
            # wait for system resources to free up
            time.sleep(0.1)
        return None 
开发者ID:MozillaSecurity,项目名称:grizzly,代码行数:25,代码来源:sapphire_worker.py

示例15: run_experiment

# 需要导入模块: import threading [as 别名]
# 或者: from threading import active_count [as 别名]
def run_experiment(agents_def):
    assert len(agents_def) == 2, 'Not enough agents (required: 2, got: %d)'\
                % len(agents_def)

    processes = []
    for agent in agents_def:
        p = Thread(target=agent_factory, kwargs=agent)
        p.daemon = True
        p.start()

        # Give the server time to start
        if agent['role'] == 0:
            sleep(1)

        processes.append(p)

    try:
        # wait until only the challenge agent is left
        while active_count() > 2:
            sleep(0.1)
    except KeyboardInterrupt:
        print('Caught control-c - shutting down.') 
开发者ID:microsoft,项目名称:malmo-challenge,代码行数:24,代码来源:pig_chase_baseline.py


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