本文整理汇总了Python中threading.currentThread方法的典型用法代码示例。如果您正苦于以下问题:Python threading.currentThread方法的具体用法?Python threading.currentThread怎么用?Python threading.currentThread使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类threading
的用法示例。
在下文中一共展示了threading.currentThread方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: import threading [as 别名]
# 或者: from threading import currentThread [as 别名]
def run(self):
print("{} has started thinking".format(threading.currentThread().getName()))
while True:
time.sleep(random.randint(1,5))
print("{} has finished thinking".format(threading.currentThread().getName()))
self.leftFork.acquire()
time.sleep(random.randint(1,5))
try:
print("{} has acquired the left fork".format(threading.currentThread().getName()))
self.rightFork.acquire()
try:
print("{} has attained both forks, currently eating".format(threading.currentThread().getName()))
finally:
self.rightFork.release()
print("{} has released the right fork".format(threading.currentThread().getName()))
finally:
self.leftFork.release()
print("{} has released the left fork".format(threading.currentThread().getName()))
示例2: set
# 需要导入模块: import threading [as 别名]
# 或者: from threading import currentThread [as 别名]
def set( self, newNumber ):
"""Set value of integer--blocks until lock acquired"""
# block until lock released then acquire lock
self.threadCondition.acquire()
# while not producer's turn, release lock and block
while self.occupiedBufferCount == 1:
print "%s tries to write." % \
threading.currentThread().getName()
self.displayState( "Buffer full. " + \
threading.currentThread().getName() + " waits." )
self.threadCondition.wait()
# (lock has now been re-acquired)
self.buffer = newNumber # set new buffer value
self.occupiedBufferCount += 1 # allow consumer to consume
self.displayState( "%s writes %d" % \
( threading.currentThread().getName(), newNumber ) )
self.threadCondition.notify() # wake up a waiting thread
self.threadCondition.release() # allow lock to be acquired
示例3: main
# 需要导入模块: import threading [as 别名]
# 或者: from threading import currentThread [as 别名]
def main():
password = getpass()
start_time = datetime.now()
hostnames = [
'arista1.twb-tech.com',
'arista2.twb-tech.com',
'arista3.twb-tech.com',
'arista4.twb-tech.com',
]
print()
print(">>>>>")
for host in hostnames:
net_device = create_device_dict(host, password)
my_thread = threading.Thread(target=scp_file, args=(net_device,))
my_thread.start()
main_thread = threading.currentThread()
for some_thread in threading.enumerate():
if some_thread != main_thread:
some_thread.join()
print(">>>>>")
print("\nElapsed time: " + str(datetime.now() - start_time))
示例4: main
# 需要导入模块: import threading [as 别名]
# 或者: from threading import currentThread [as 别名]
def main():
'''
Use threads and Netmiko to connect to each of the devices in the database. Execute
'show version' on each device. Record the amount of time required to do this.
'''
start_time = datetime.now()
devices = NetworkDevice.objects.all()
for a_device in devices:
my_thread = threading.Thread(target=show_version, args=(a_device,))
my_thread.start()
main_thread = threading.currentThread()
for some_thread in threading.enumerate():
if some_thread != main_thread:
print(some_thread)
some_thread.join()
print("\nElapsed time: " + str(datetime.now() - start_time))
示例5: InterruptibleSleep
# 需要导入模块: import threading [as 别名]
# 或者: from threading import currentThread [as 别名]
def InterruptibleSleep(sleep_time):
"""Puts thread to sleep, checking this threads exit_flag four times a second.
Args:
sleep_time: Time to sleep.
"""
slept = 0.0
epsilon = .0001
thread = threading.currentThread()
while slept < sleep_time - epsilon:
remaining = sleep_time - slept
this_sleep_time = min(remaining, 0.25)
time.sleep(this_sleep_time)
slept += this_sleep_time
if thread.exit_flag:
return
示例6: StartWork
# 需要导入模块: import threading [as 别名]
# 或者: from threading import currentThread [as 别名]
def StartWork(self):
"""Starts a critical section in which the number of workers is limited.
Starts a critical section which allows self.__enabled_count
simultaneously operating threads. The critical section is ended by
calling self.FinishWork().
"""
self.__thread_semaphore.acquire()
if self.__backoff_time > 0.0:
if not threading.currentThread().exit_flag:
logger.info('[%s] Backing off due to errors: %.1f seconds',
threading.currentThread().getName(),
self.__backoff_time)
self.__sleep(self.__backoff_time)
示例7: InterruptibleSleep
# 需要导入模块: import threading [as 别名]
# 或者: from threading import currentThread [as 别名]
def InterruptibleSleep(sleep_time):
"""Puts thread to sleep, checking this threads exit_flag twice a second.
Args:
sleep_time: Time to sleep.
"""
slept = 0.0
epsilon = .0001
thread = threading.currentThread()
while slept < sleep_time - epsilon:
remaining = sleep_time - slept
this_sleep_time = min(remaining, 0.5)
time.sleep(this_sleep_time)
slept += this_sleep_time
if thread.exit_flag:
return
示例8: _OpenSecondaryConnection
# 需要导入模块: import threading [as 别名]
# 或者: from threading import currentThread [as 别名]
def _OpenSecondaryConnection(self):
"""Possibly open a database connection for the secondary thread.
If the connection is not open (for the calling thread, which is assumed
to be the unique secondary thread), then open it. We also open a couple
cursors for later use (and reuse).
"""
if self.secondary_conn:
return
assert not _RunningInThread(self.primary_thread)
self.secondary_thread = threading.currentThread()
self.secondary_conn = sqlite3.connect(self.db_filename)
self.insert_cursor = self.secondary_conn.cursor()
self.update_cursor = self.secondary_conn.cursor()
示例9: via_annotation_stream
# 需要导入模块: import threading [as 别名]
# 或者: from threading import currentThread [as 别名]
def via_annotation_stream(uri):
name = threading.currentThread().name
start = time.time()
total_size = 0
print("thread {0} downloading via annotation stream...".format(name))
with Proxy(uri) as p:
perform_checksum = False
for progress, checksum in p.annotation_stream(perform_checksum):
chunk = current_context.response_annotations["FDAT"]
if perform_checksum and zlib.crc32(chunk) != checksum:
raise ValueError("checksum error")
total_size += len(chunk)
assert progress == total_size
current_context.response_annotations.clear() # clean them up once we're done with them
duration = time.time() - start
print("thread {0} done, {1:.2f} Mb/sec.".format(name, total_size/1024.0/1024.0/duration))
示例10: get_current_language
# 需要导入模块: import threading [as 别名]
# 或者: from threading import currentThread [as 别名]
def get_current_language(self):
redis = self.redis.get(threading.currentThread())
secure_cookie = self.get_secure_cookie(DEFAULT_COOKIE_TOKEN_NAME)
if secure_cookie is None:
return DEFAULT_LANGUAGE
auth_key = bytes.decode(secure_cookie)
params = redis.get(auth_key)
if params is None:
return DEFAULT_LANGUAGE
params = json.loads(params)
redis.expire(auth_key, 86400)
return params.get("language", DEFAULT_LANGUAGE)
示例11: get_current_user
# 需要导入模块: import threading [as 别名]
# 或者: from threading import currentThread [as 别名]
def get_current_user(self):
redis = self.redis.get(threading.currentThread())
secure_cookie = self.get_secure_cookie("token")
if secure_cookie is None:
return None
auth_key = bytes.decode(secure_cookie)
params = redis.get(auth_key)
if params is None:
return None
params = json.loads(params)
redis.expire(auth_key, server.REDIS_DEFAULT_EXPIRE)
return params.get("user", None)
示例12: get_current_host
# 需要导入模块: import threading [as 别名]
# 或者: from threading import currentThread [as 别名]
def get_current_host(self):
redis = self.redis.get(threading.currentThread())
secure_cookie = self.get_secure_cookie("token")
if secure_cookie is None:
raise tornado.web.HTTPError(403, "Authentication Failed")
auth_key = bytes.decode(secure_cookie)
params = redis.get(auth_key)
if params is None:
raise tornado.web.HTTPError(403, "Authentication Failed")
redis.expire(auth_key, 86400)
params = json.loads(params)
return params['server']
示例13: get_current_password
# 需要导入模块: import threading [as 别名]
# 或者: from threading import currentThread [as 别名]
def get_current_password(self):
redis = self.redis.get(threading.currentThread())
secure_cookie = self.get_secure_cookie("token")
if secure_cookie is None:
raise tornado.web.HTTPError(403, "Authentication Failed")
auth_key = bytes.decode(secure_cookie)
params = redis.get(auth_key)
if params is None:
raise tornado.web.HTTPError(403, "Authentication Failed")
redis.expire(auth_key, 86400)
params = json.loads(params)
return params['password']
示例14: wrap_catch
# 需要导入模块: import threading [as 别名]
# 或者: from threading import currentThread [as 别名]
def wrap_catch(method):
def catch(*args, **kwargs):
self = args[0]
try:
return method(*args, **kwargs)
except Exception as e:
msg = "Catched Error in FM Main request thread"
logger = logging.getLogger('tornado.application')
logger.error("Error in FM Main: %s, %s, traceback = %s" % (msg, str(e), traceback.format_exc()))
self.redis.close(threading.currentThread())
self._handle_request_exception(e)
return catch
示例15: authenticate_by_pam
# 需要导入模块: import threading [as 别名]
# 或者: from threading import currentThread [as 别名]
def authenticate_by_pam(request, username, password):
rpc_request = FM.BaseAction.get_rpc_request()
result = rpc_request.request('main/authenticate', login=username, password=password)
answer = FM.BaseAction.process_result(result)
if not answer.get('Error', False) and answer.get('data').get('status', False):
try:
redis = request.redis.get(threading.currentThread())
""":type : connectors.RedisConnector.RedisConnector"""
token = 'FM::session::' + username + '::' + random_hash()
params = {
"server": "localhost",
"user": username,
"password": password
}
redis.set(token, json.dumps(params))
request.set_secure_cookie(DEFAULT_COOKIE_TOKEN_NAME, token, COOKIE_EXPIRE)
return token
except Exception as e:
request.application.logger.error(
"Error in FMAuth: %s, traceback = %s" % (str(e), traceback.format_exc()))
return False
return False