• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python threading.get_ident函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中threading.get_ident函数的典型用法代码示例。如果您正苦于以下问题:Python get_ident函数的具体用法?Python get_ident怎么用?Python get_ident使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: __setattr__

 def __setattr__(self, name, value):
     if name in ('_lock', '_root', '_proxies'):
         super(ThreadProxy, self).__setattr__(name, value)
     elif threading.get_ident() in self._proxies:
         setattr(self.proxiesp[threading.get_ident()], name, value)
     else:
         raise AttributeError("no proxy for current thread")
开发者ID:jeinstos,项目名称:pypsi,代码行数:7,代码来源:server.py


示例2: execute

 def execute(self, raw_req):
     try:
         self._lock.acquire()
         print('=====================>>>>>enter', threading.get_ident())
         return self._execute(raw_req)
     finally:
         self._lock.release()
         print('<<<<<<=================leave', threading.get_ident())
开发者ID:touilleMan,项目名称:mongaule,代码行数:8,代码来源:db.py


示例3: waitResult

 def waitResult(self):
   """ Wait for the execution of the last enqueued job to be done, and return the result or raise an exception. """
   self.thread.execute_queue.join()
   try:
     e = self.thread.exception_queue[threading.get_ident()].get_nowait()
   except queue.Empty:
     return self.thread.result_queue[threading.get_ident()].get_nowait()
   else:
     raise e
开发者ID:desbma,项目名称:web_cache,代码行数:9,代码来源:__init__.py


示例4: trywrapper

 def trywrapper(self, f, msginfo):
     msginfo["_function_id"] = f.__name__
     thread_details[threading.get_ident()] = msginfo.copy()
     try:
         f(msg=msginfo)
     except Exception as e:
         traceback.print_exc()
         if msginfo.get("msg"):
             send("Error executing {}: {}".format(f, e))
     del thread_details[threading.get_ident()]
开发者ID:MrW24,项目名称:JiyuuBot,代码行数:10,代码来源:__init__.py


示例5: _check_thread

 def _check_thread(self):
     try:
         if self.__thread_ident == threading.get_ident():
             return
     except AttributeError:
         pass
     else:
         raise ProgrammingError(
             "SQLite objects created in a thread can only be used in that "
             "same thread. The object was created in thread id %d and this "
             "is thread id %d" % (self.__thread_ident, threading.get_ident()))
开发者ID:timm,项目名称:timmnix,代码行数:11,代码来源:_sqlite3.py


示例6: db_conn

    def db_conn(self):
        """
        Refers to a database connection via thread identifier
        :return: database connection handle
        """

        # Does a connection exist for this thread
        if threading.get_ident() not in self._db.keys():
            self.connect()

        return self._db[threading.get_ident()]
开发者ID:djamp42,项目名称:librenms,代码行数:11,代码来源:__init__.py


示例7: __apply_gradients

    def __apply_gradients(self):
        logger.info('{}: training - apply gradients begin'.format(
            threading.get_ident()))

        gradients_begin = time.time()
        # zero gradient accumulators
        ModelBuilder.zero_model_gradient_accumulators()
        if args.debug:
            ModelBuilder.model_gradient_accumulators_debug_info()

        # calculate move rate gradients
        move_rate_values = []
        ucb_move_rate_values = []
        ugtsa_move_rate_values = []
        for move_rate, (
                move_rate_value,
                oracle_ucb_move_rate_value,
                oracle_ugtsa_move_rate_value) in sorted(
                    self.shared_state.move_rate_dict.items()):
            move_rate_values += [move_rate_value]
            ucb_move_rate_values += [oracle_ucb_move_rate_value]
            ugtsa_move_rate_values += [oracle_ugtsa_move_rate_value]

        loss, move_rates_gradient = ModelBuilder.cost_function(
            move_rate_values, ucb_move_rate_values, ugtsa_move_rate_values)

        logger.info('loss {}'.format(loss))
        if args.debug:
            print(move_rates_gradient)

        # accumulate gradients
        self.ugtsa_algorithm.computation_graph.model_gradients(
            first_node=self.shared_state.first_node,
            y_grads={
                move_rate: gradient
                for (move_rate, _), gradient in zip(
                    sorted(self.shared_state.move_rate_dict.items()),
                    move_rates_gradient)})

        # apply gradients
        ModelBuilder.apply_gradients()
        if args.debug:
            ModelBuilder.model_gradient_accumulators_debug_info()
        gradients_end = time.time()
        logger.info('gradients took {}'.format(
            gradients_end - gradients_begin))

        self.shared_state.first_node = len(
            self.ugtsa_algorithm.computation_graph.computation_graph.nodes)
        self.shared_state.move_rate_dict = {}

        logger.info('{}: training - apply gradients end'.format(
            threading.get_ident()))
开发者ID:thomasste,项目名称:ugtsa,代码行数:53,代码来源:solution_002.py


示例8: connect

    def connect(self):
        logger.info('Attempting to connect to redis with ident={}, thread={}'.format(
            self.ident, threading.get_ident()))
        if self.redis_url is None:
            raise RedisConnectionError('self.redis_url not set')

        self.redis = redis.StrictRedis.from_url(self.redis_url,
                                                decode_responses=True)

        self.register_scripts()
        logger.info('Redis connection successful with ident={}, thread={}'.format(
            self.ident, threading.get_ident()))
开发者ID:ArchiveTeam,项目名称:ArchiveBot,代码行数:12,代码来源:control.py


示例9: trywrapper

 def trywrapper(self, f, msginfo):
     msginfo["_function_id"] = f.__name__
     thread_details[threading.get_ident()] = msginfo.copy()
     try:
         if len(inspect.signature(f).parameters) > 0:
             f(msginfo)
         else:
             f()
     except Exception as e:
         traceback.print_exc()
         if msginfo.get("msg"):
             send("Error executing {}: {}".format(command, e))
     del thread_details[threading.get_ident()]
开发者ID:Flat,项目名称:JiyuuBot,代码行数:13,代码来源:__init__.py


示例10: run_fork

def run_fork():
    lock = threading.Lock()
    child_t = threading.Thread(target=child_thread, args=(lock,))
    child_t.start()
    print('main thread identity', threading.get_ident())
    pid = os.fork()
    if pid == -1:
        raise RuntimeError('fork failed.')

    if pid == 0:
        print('main thread identity', threading.get_ident())
        child_worker(lock)
    else:
        time.sleep(120)
开发者ID:justdoit0823,项目名称:notes,代码行数:14,代码来源:lock-in-process.py


示例11: func_assig_thread

 def func_assig_thread(self, O, all_threads):
     if threading.get_ident() in all_threads:
         th = all_threads[threading.get_ident()]
     else:
         all_threads[threading.get_ident()] = all_threads['count']
         th = all_threads['count']
         all_threads['count'] += 1
     x = skimming_single_origin(O, self.graph, self.results, self.aux_res, th)
     self.cumulative += 1
     if x != O:
         self.report.append(x)
     if pyqt:
         self.skimming.emit(['zones finalized', self.cumulative])
         txt = str(self.cumulative) + ' / ' + str(self.matrix.zones)
         self.skimming.emit(['text skimming', txt])
开发者ID:AequilibraE,项目名称:AequilibraE,代码行数:15,代码来源:network_skimming.py


示例12: pr

 def pr(self, name, a=None, kw=None):
     f = sys._getframe(2)
     if f.f_code.co_filename.endswith('ZODB/utils.py'):
         f = sys._getframe(3)
     f = '%s:%s' % (f.f_code.co_filename, f.f_lineno)
     print(id(self), self._lock, threading.get_ident(), f, name,
           a if a else '', kw if kw else '')
开发者ID:vpelletier,项目名称:ZODB,代码行数:7,代码来源:utils.py


示例13: async_start

    async def async_start(self) -> None:
        """Finalize startup from inside the event loop.

        This method is a coroutine.
        """
        _LOGGER.info("Starting Home Assistant")
        self.state = CoreState.starting

        setattr(self.loop, '_thread_ident', threading.get_ident())
        self.bus.async_fire(EVENT_HOMEASSISTANT_START)

        try:
            # Only block for EVENT_HOMEASSISTANT_START listener
            self.async_stop_track_tasks()
            with timeout(TIMEOUT_EVENT_START):
                await self.async_block_till_done()
        except asyncio.TimeoutError:
            _LOGGER.warning(
                'Something is blocking Home Assistant from wrapping up the '
                'start up phase. We\'re going to continue anyway. Please '
                'report the following info at http://bit.ly/2ogP58T : %s',
                ', '.join(self.config.components))

        # Allow automations to set up the start triggers before changing state
        await asyncio.sleep(0)

        if self.state != CoreState.starting:
            _LOGGER.warning(
                'Home Assistant startup has been interrupted. '
                'Its state may be inconsistent.')
            return

        self.state = CoreState.running
        _async_create_timer(self)
开发者ID:arsaboo,项目名称:home-assistant,代码行数:34,代码来源:core.py


示例14: _test_factory

 def _test_factory(fifo, start):
     start.wait()
     factory = warehouse.http.ThreadLocalSessionFactory()
     # the actual session instance is stuck into the queue here as to
     # maintain a reference so it's not gc'd (which can result in id
     # reuse)
     fifo.put((threading.get_ident(), factory(_REQUEST)))
开发者ID:craig5,项目名称:warehouse,代码行数:7,代码来源:test_http.py


示例15: __enter__

 def __enter__(self):
     id = threading.get_ident()
     if id not in self.calls:
         self.calls[id] = 0
         self.prec[id] = float('-inf')
     self.calls[id] += 1
     return self
开发者ID:wxgeo,项目名称:geophar,代码行数:7,代码来源:custom_objects.py


示例16: async_test_home_assistant

def async_test_home_assistant(loop):
    """Return a Home Assistant object pointing at test config dir."""
    loop._thread_ident = threading.get_ident()

    hass = ha.HomeAssistant(loop)
    hass.async_track_tasks()

    hass.config.location_name = 'test home'
    hass.config.config_dir = get_test_config_dir()
    hass.config.latitude = 32.87336
    hass.config.longitude = -117.22743
    hass.config.elevation = 0
    hass.config.time_zone = date_util.get_time_zone('US/Pacific')
    hass.config.units = METRIC_SYSTEM
    hass.config.skip_pip = True

    if 'custom_components.test' not in loader.AVAILABLE_COMPONENTS:
        yield from loop.run_in_executor(None, loader.prepare, hass)

    hass.state = ha.CoreState.running

    # Mock async_start
    orig_start = hass.async_start

    @asyncio.coroutine
    def mock_async_start():
        """Start the mocking."""
        with patch('homeassistant.core._async_create_timer'):
            yield from orig_start()

    hass.async_start = mock_async_start

    return hass
开发者ID:arjenfvellinga,项目名称:home-assistant,代码行数:33,代码来源:common.py


示例17: run_loop

 def run_loop():
     """Run event loop."""
     # pylint: disable=protected-access
     loop._thread_ident = threading.get_ident()
     loop.run_forever()
     loop.close()
     stop_event.set()
开发者ID:arjenfvellinga,项目名称:home-assistant,代码行数:7,代码来源:common.py


示例18: current_frames_with_threads

    def current_frames_with_threads(self):
        import threading
        import traceback

        # Spawn a thread that blocks at a known place.  Then the main
        # thread does sys._current_frames(), and verifies that the frames
        # returned make sense.
        entered_g = threading.Event()
        leave_g = threading.Event()
        thread_info = []  # the thread's id

        def f123():
            g456()

        def g456():
            thread_info.append(threading.get_ident())
            entered_g.set()
            leave_g.wait()

        t = threading.Thread(target=f123)
        t.start()
        entered_g.wait()

        # At this point, t has finished its entered_g.set(), although it's
        # impossible to guess whether it's still on that line or has moved on
        # to its leave_g.wait().
        self.assertEqual(len(thread_info), 1)
        thread_id = thread_info[0]

        d = sys._current_frames()

        main_id = threading.get_ident()
        self.assertIn(main_id, d)
        self.assertIn(thread_id, d)

        # Verify that the captured main-thread frame is _this_ frame.
        frame = d.pop(main_id)
        self.assertTrue(frame is sys._getframe())

        # Verify that the captured thread frame is blocked in g456, called
        # from f123.  This is a litte tricky, since various bits of
        # threading.py are also in the thread's call stack.
        frame = d.pop(thread_id)
        stack = traceback.extract_stack(frame)
        for i, (filename, lineno, funcname, sourceline) in enumerate(stack):
            if funcname == "f123":
                break
        else:
            self.fail("didn't find f123() on thread's call stack")

        self.assertEqual(sourceline, "g456()")

        # And the next record must be for g456().
        filename, lineno, funcname, sourceline = stack[i+1]
        self.assertEqual(funcname, "g456")
        self.assertIn(sourceline, ["leave_g.wait()", "entered_g.set()"])

        # Reap the spawned thread.
        leave_g.set()
        t.join()
开发者ID:MaximVanyushkin,项目名称:Sharp.RemoteQueryable,代码行数:60,代码来源:test_sys.py


示例19: process_request

    def process_request(self, request):

        # Todo: remove when IE9 support will expire.
        request.ie_ajax_iframe = request.method == 'POST' and \
                 'HTTP_X_REQUESTED_WITH' not in request.META and \
                'HTTP_X_REQUESTED_WITH' in request.POST
        if request.ie_ajax_iframe:
            # Fix IE9 not being able to post $.ajaxForm() with proper HTTP headers due to iframe emulation.
            request.META['HTTP_X_REQUESTED_WITH'] = request.POST['HTTP_X_REQUESTED_WITH']

        # Get local timezone from browser and activate it.
        if getattr(settings, 'USE_JS_TIMEZONE', False):
            tz_name = self.__class__.get_request_timezone(request)
            if tz_name is not None:
                timezone.activate(pytz.timezone(tz_name))

        self.__class__._threadmap[threading.get_ident()] = request

        # Optional server-side injected JSON.
        request.client_data = {}
        """
            request.client_routes = [
                'logout',
                'users_list',
            ]
        """
        request.client_routes = []
        vm_list = to_vm_list(request.client_data)
        if has_vm_list(request.session):
            vm_session = to_vm_list(request.session)
            vm_list.extend(vm_session)
开发者ID:Dmitri-Sintsov,项目名称:django-jinja-knockout,代码行数:31,代码来源:middleware.py


示例20: do_work

def do_work(num):
	#Pretend to do work
	#time.sleep(0.1)
	with lock:
		print(num)
		print("Current thread:", str(threading.current_thread()).split(",")[0].split("-")[1]) #Prints just the thread number, not identifier. The order the threads were created in is the number starting at 1
		print("Thread ident:", threading.get_ident())
开发者ID:mitchtz,项目名称:Daily_Programmer,代码行数:7,代码来源:thread_test.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python threading.local函数代码示例发布时间:2022-05-27
下一篇:
Python threading.enumerate函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap