本文整理汇总了Python中threading.get_ident函数的典型用法代码示例。如果您正苦于以下问题:Python get_ident函数的具体用法?Python get_ident怎么用?Python get_ident使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_ident函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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")
示例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())
示例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
示例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()]
示例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()))
示例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()]
示例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()))
示例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()))
示例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()]
示例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)
示例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])
示例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 '')
示例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)
示例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)))
示例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