當前位置: 首頁>>代碼示例>>Python>>正文


Python threading.currentThread方法代碼示例

本文整理匯總了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())) 
開發者ID:PacktPublishing,項目名稱:Learning-Concurrency-in-Python,代碼行數:21,代碼來源:diningPhilosophers.py

示例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 
開發者ID:PythonClassRoom,項目名稱:PythonClassBook,代碼行數:26,代碼來源:SynchronizedInteger.py

示例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)) 
開發者ID:ktbyers,項目名稱:python_course,代碼行數:27,代碼來源:exercise2_with_threads.py

示例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)) 
開發者ID:ktbyers,項目名稱:python_course,代碼行數:21,代碼來源:ex6_threads_show_ver.py

示例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 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:18,代碼來源:adaptive_thread_pool.py

示例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) 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:18,代碼來源:adaptive_thread_pool.py

示例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 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:18,代碼來源:bulkloader.py

示例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() 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:27,代碼來源:bulkloader.py

示例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)) 
開發者ID:irmen,項目名稱:Pyro5,代碼行數:18,代碼來源:client.py

示例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) 
開發者ID:LTD-Beget,項目名稱:sprutio,代碼行數:20,代碼來源:BaseHandler.py

示例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) 
開發者ID:LTD-Beget,項目名稱:sprutio,代碼行數:19,代碼來源:BaseHandler.py

示例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'] 
開發者ID:LTD-Beget,項目名稱:sprutio,代碼行數:19,代碼來源:BaseHandler.py

示例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'] 
開發者ID:LTD-Beget,項目名稱:sprutio,代碼行數:20,代碼來源:BaseHandler.py

示例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 
開發者ID:LTD-Beget,項目名稱:sprutio,代碼行數:18,代碼來源:BaseHandler.py

示例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 
開發者ID:LTD-Beget,項目名稱:sprutio,代碼行數:27,代碼來源:FMAuth.py


注:本文中的threading.currentThread方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。