本文整理汇总了Python中threading.get_ident方法的典型用法代码示例。如果您正苦于以下问题:Python threading.get_ident方法的具体用法?Python threading.get_ident怎么用?Python threading.get_ident使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类threading
的用法示例。
在下文中一共展示了threading.get_ident方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import threading [as 别名]
# 或者: from threading import get_ident [as 别名]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.max_size = None
# an empty dispatcher to prevent crashes
self._dispatch = lambda *args: None
# generic event listeners
self._dispatch_listeners = []
# the keep alive
self._keep_alive = None
self.thread_id = threading.get_ident()
# ws related stuff
self.session_id = None
self.sequence = None
self._zlib = zlib.decompressobj()
self._buffer = bytearray()
示例2: get_from_db_key_value_store
# 需要导入模块: import threading [as 别名]
# 或者: from threading import get_ident [as 别名]
def get_from_db_key_value_store(key):
global KV_META_CACHE
kv_log.info("Getting '%s' from kv store", key)
if key in KV_META_CACHE:
return KV_META_CACHE[key]
thread_id = "kv_store_{}".format(threading.get_ident())
with session_context(thread_id) as sess:
have = sess.query(KeyValueStore).filter(KeyValueStore.key == key).scalar()
if have:
kv_log.info("KV store had entry")
ret = have.value
else:
kv_log.info("KV store did not have entry")
ret = {}
sess.commit()
return ret
示例3: get_os_tid
# 需要导入模块: import threading [as 别名]
# 或者: from threading import get_ident [as 别名]
def get_os_tid():
"""
Get the Linux process id associated with the current thread
Returns:
int: The process id
"""
if sys.platform.startswith(u'linux'):
return ctypes.CDLL(u'libc.so.6').syscall(186)
else:
# TODO: This is hacky - we need to replace it with something that actually returns the OS thread ID
if is_python_2():
return threading._get_ident()
else:
return threading.get_ident()
示例4: api
# 需要导入模块: import threading [as 别名]
# 或者: from threading import get_ident [as 别名]
def api(self, cmd, errcheck=True, block=False, timeout=0.5):
'''Invoke api command (with error checking by default).
'''
if not self.connected():
raise ConnectionError("Call ``connect()`` first")
self.log.debug("api cmd '{}'".format(cmd))
if not block and (get_ident() == self.loop._tid):
# note this is an `asyncio.Future`
return self.protocol.api(cmd, errcheck=errcheck)
# NOTE: this is a `concurrent.futures.Future`
future = run_in_order_threadsafe(
[self.protocol.api(cmd, errcheck=errcheck)],
self.loop,
timeout=timeout,
block=block,
)
if not block:
return future
return future.result(0.005)
示例5: _get_connection
# 需要导入模块: import threading [as 别名]
# 或者: from threading import get_ident [as 别名]
def _get_connection(self):
"""
Returns a singular database connection to be shared amongst all calls.
"""
curr_thread = threading.get_ident()
if curr_thread not in self.conn or self.conn[curr_thread] is None:
try:
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
self.conn[curr_thread] = conn
except sqlite3.Error as e:
shared_utils.print_and_log(
logging.ERROR,
"Could not get db connection, failing: {}".format(repr(e)),
should_print=True,
)
raise e
return self.conn[curr_thread]
示例6: _one_thread
# 需要导入模块: import threading [as 别名]
# 或者: from threading import get_ident [as 别名]
def _one_thread(self) -> None:
current_thread_id = threading.get_ident()
if current_thread_id == self._ThreadID:
return
log.show_value(
self.config,
log.level.DEBUG,
'ThreadID',
self._ThreadID
)
log.show_value(
self.config,
log.level.DEBUG,
'Current thread id',
current_thread_id
)
raise exceptions.MultiThreadOperated()
示例7: run_forever
# 需要导入模块: import threading [as 别名]
# 或者: from threading import get_ident [as 别名]
def run_forever(self):
"""Run until stop() is called."""
self._check_closed()
if self.is_running():
raise RuntimeError('Event loop is running.')
self._set_coroutine_wrapper(self._debug)
self._thread_id = threading.get_ident()
try:
while True:
self._run_once()
if self._stopping:
break
finally:
self._stopping = False
self._thread_id = None
self._set_coroutine_wrapper(False)
示例8: _check_thread
# 需要导入模块: import threading [as 别名]
# 或者: from threading import get_ident [as 别名]
def _check_thread(self):
"""Check that the current thread is the thread running the event loop.
Non-thread-safe methods of this class make this assumption and will
likely behave incorrectly when the assumption is violated.
Should only be called when (self._debug == True). The caller is
responsible for checking this condition for performance reasons.
"""
if self._thread_id is None:
return
thread_id = threading.get_ident()
if thread_id != self._thread_id:
raise RuntimeError(
"Non-thread-safe operation invoked on an event loop other "
"than the current one")
示例9: task
# 需要导入模块: import threading [as 别名]
# 或者: from threading import get_ident [as 别名]
def task(N, done, done_tasks, errors):
try:
# We don't use modulefinder but still import it in order to stress
# importing of different modules from several threads.
if len(done_tasks) % 2:
import modulefinder
import random
else:
import random
import modulefinder
# This will fail if random is not completely initialized
x = random.randrange(1, 3)
except Exception as e:
errors.append(e.with_traceback(None))
finally:
done_tasks.append(threading.get_ident())
finished = len(done_tasks) == N
if finished:
done.set()
# Create a circular import structure: A -> C -> B -> D -> A
# NOTE: `time` is already loaded and therefore doesn't threaten to deadlock.
示例10: test_pthread_kill_main_thread
# 需要导入模块: import threading [as 别名]
# 或者: from threading import get_ident [as 别名]
def test_pthread_kill_main_thread(self):
# Test that a signal can be sent to the main thread with pthread_kill()
# before any other thread has been created (see issue #12392).
code = """if True:
import threading
import signal
import sys
def handler(signum, frame):
sys.exit(3)
signal.signal(signal.SIGUSR1, handler)
signal.pthread_kill(threading.get_ident(), signal.SIGUSR1)
sys.exit(2)
"""
with spawn_python('-c', code) as process:
stdout, stderr = process.communicate()
exitcode = process.wait()
if exitcode != 3:
raise Exception("Child error (exit code %s): %s" %
(exitcode, stdout))
示例11: test_main_thread_after_fork
# 需要导入模块: import threading [as 别名]
# 或者: from threading import get_ident [as 别名]
def test_main_thread_after_fork(self):
code = """if 1:
import os, threading
pid = os.fork()
if pid == 0:
main = threading.main_thread()
print(main.name)
print(main.ident == threading.current_thread().ident)
print(main.ident == threading.get_ident())
else:
os.waitpid(pid, 0)
"""
_, out, err = assert_python_ok("-c", code)
data = out.decode().replace('\r', '')
self.assertEqual(err, b"")
self.assertEqual(data, "MainThread\nTrue\nTrue\n")
示例12: test_main_thread_after_fork_from_nonmain_thread
# 需要导入模块: import threading [as 别名]
# 或者: from threading import get_ident [as 别名]
def test_main_thread_after_fork_from_nonmain_thread(self):
code = """if 1:
import os, threading, sys
def f():
pid = os.fork()
if pid == 0:
main = threading.main_thread()
print(main.name)
print(main.ident == threading.current_thread().ident)
print(main.ident == threading.get_ident())
# stdout is fully buffered because not a tty,
# we have to flush before exit.
sys.stdout.flush()
else:
os.waitpid(pid, 0)
th = threading.Thread(target=f)
th.start()
th.join()
"""
_, out, err = assert_python_ok("-c", code)
data = out.decode().replace('\r', '')
self.assertEqual(err, b"")
self.assertEqual(data, "Thread-1\nTrue\nTrue\n")
示例13: test_thread_state
# 需要导入模块: import threading [as 别名]
# 或者: from threading import get_ident [as 别名]
def test_thread_state(self):
# some extra thread-state tests driven via _testcapi
def target():
idents = []
def callback():
idents.append(threading.get_ident())
_testcapi._test_thread_state(callback)
a = b = callback
time.sleep(1)
# Check our main thread is in the list exactly 3 times.
self.assertEqual(idents.count(threading.get_ident()), 3,
"Couldn't find main thread correctly in the list")
target()
t = threading.Thread(target=target)
t.start()
t.join()
示例14: run
# 需要导入模块: import threading [as 别名]
# 或者: from threading import get_ident [as 别名]
def run(self, background=False):
"""
Method to start the worker.
Parameters
----------
background: bool
If set to False (Default). the worker is executed in the current thread.
If True, a new daemon thread is created that runs the worker. This is
useful in a single worker scenario/when the compute function only simulates
work.
"""
if background:
self.worker_id += str(threading.get_ident())
self.thread = threading.Thread(target=self._run, name='worker %s thread'%self.worker_id)
self.thread.daemon=True
self.thread.start()
else:
self._run()
示例15: _get_connection
# 需要导入模块: import threading [as 别名]
# 或者: from threading import get_ident [as 别名]
def _get_connection(self):
"""Returns a singular database connection to be shared amongst all
calls
"""
curr_thread = threading.get_ident()
if curr_thread not in self.conn or self.conn[curr_thread] is None:
try:
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
self.conn[curr_thread] = conn
except sqlite3.Error as e:
shared_utils.print_and_log(
logging.ERROR,
"Could not get db connection, failing: {}".format(repr(e)),
should_print=True,
)
raise e
return self.conn[curr_thread]