Python threading.currentThread() Examples

The following are 30 code examples for showing how to use threading.currentThread(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module threading , or try the search function .

Example 1
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: diningPhilosophers.py    License: MIT License 6 votes vote down vote up
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())) 
Example 2
Project: PythonClassBook   Author: PythonClassRoom   File: SynchronizedInteger.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 3
Project: python_course   Author: ktbyers   File: exercise2_with_threads.py    License: Apache License 2.0 6 votes vote down vote up
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)) 
Example 4
Project: python_course   Author: ktbyers   File: ex6_threads_show_ver.py    License: Apache License 2.0 6 votes vote down vote up
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)) 
Example 5
Project: browserscope   Author: elsigh   File: adaptive_thread_pool.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 6
Project: browserscope   Author: elsigh   File: adaptive_thread_pool.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 7
Project: browserscope   Author: elsigh   File: bulkloader.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 8
Project: browserscope   Author: elsigh   File: bulkloader.py    License: Apache License 2.0 6 votes vote down vote up
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() 
Example 9
Project: Pyro5   Author: irmen   File: client.py    License: MIT License 6 votes vote down vote up
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)) 
Example 10
Project: sprutio   Author: LTD-Beget   File: BaseHandler.py    License: GNU General Public License v3.0 6 votes vote down vote up
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) 
Example 11
Project: sprutio   Author: LTD-Beget   File: BaseHandler.py    License: GNU General Public License v3.0 6 votes vote down vote up
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) 
Example 12
Project: sprutio   Author: LTD-Beget   File: BaseHandler.py    License: GNU General Public License v3.0 6 votes vote down vote up
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'] 
Example 13
Project: sprutio   Author: LTD-Beget   File: BaseHandler.py    License: GNU General Public License v3.0 6 votes vote down vote up
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'] 
Example 14
Project: sprutio   Author: LTD-Beget   File: BaseHandler.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 15
Project: sprutio   Author: LTD-Beget   File: FMAuth.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 16
Project: sprutio   Author: LTD-Beget   File: FMAuth.py    License: GNU General Public License v3.0 6 votes vote down vote up
def authenticate_by_token(request, token):
        redis = request.redis.get(threading.currentThread())
        """:type : connectors.RedisConnector.RedisConnector"""
        if redis.exists(str(token)):
            try:
                params = redis.get(token)
                params = json.loads(str(params))
                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 
Example 17
Project: ironpython2   Author: IronLanguages   File: test_thread.py    License: Apache License 2.0 6 votes vote down vote up
def readerThread(self, d, readerNum):
        if sys.version_info[0] < 3 :
            name = currentThread().getName()
        else :
            name = currentThread().name

        for i in xrange(5) :
            c = d.cursor()
            count = 0
            rec = c.first()
            while rec:
                count += 1
                key, data = rec
                self.assertEqual(self.makeData(key), data)
                rec = c.next()
            if verbose:
                print "%s: found %d records" % (name, count)
            c.close()

        if verbose:
            print "%s: thread finished" % name 
Example 18
Project: ironpython2   Author: IronLanguages   File: test_thread.py    License: Apache License 2.0 6 votes vote down vote up
def writerThread(self, d, keys, readers):
        if sys.version_info[0] < 3 :
            name = currentThread().getName()
        else :
            name = currentThread().name
        if verbose:
            print "%s: creating records %d - %d" % (name, start, stop)

        count=len(keys)//len(readers)
        count2=count
        for x in keys :
            key = '%04d' % x
            dbutils.DeadlockWrap(d.put, key, self.makeData(key),
                                 max_retries=12)

            if verbose and x % 100 == 0:
                print "%s: records %d - %d finished" % (name, start, x)

            count2-=1
            if not count2 :
                readers.pop().start()
                count2=count

        if verbose:
            print "%s: thread finished" % name 
Example 19
Project: P4wnP1   Author: RoganDawes   File: LinkLayer.py    License: GNU General Public License v3.0 6 votes vote down vote up
def stop(self):
		dispatcher.send(data = "LinkLayer stopping..", signal = LinkLayer.SIGNAL_LINKLAYER_STOPPING, sender = LinkLayer.DISPATCHER_SENDER_NAME)
		self.state["EVENT_STOP_WRITE"].set()
		self.state["EVENT_STOP_READ"].set()
		# terminate read thread if set
		if self.state.has_key("read_thread"):
			try:
				self.state["read_thread"].join()
			except RuntimeError:
				pass # same thread or not started
		# terminate write thread if set
		if self.state.has_key("write_thread") and threading.currentThread != self.state["write_thread"]:
			try:
				self.state["write_thread"].join()
			except RuntimeError:
				pass # same thread or not started

		dispatcher.send(data = "LinkLayer stopped", signal = LinkLayer.SIGNAL_LINKLAYER_STOPPED, sender = LinkLayer.DISPATCHER_SENDER_NAME) 
Example 20
Project: sndlatr   Author: Schibum   File: imaplib2.py    License: Apache License 2.0 6 votes vote down vote up
def _log(self, lvl, line):
            if lvl > self.debug:
                return

            if line[-2:] == CRLF:
                line = line[:-2] + '\\r\\n'

            tn = threading.currentThread().getName()

            if lvl <= 1 or self.debug > self.debug_buf_lvl:
                self.debug_lock.acquire()
                self._mesg(line, tn)
                self.debug_lock.release()
                if lvl != 1:
                    return

            # Keep log of last `_cmd_log_len' interactions for debugging.
            self.debug_lock.acquire()
            self._cmd_log[self._cmd_log_idx] = (line, tn, time.time())
            self._cmd_log_idx += 1
            if self._cmd_log_idx >= self._cmd_log_len:
                self._cmd_log_idx = 0
            self.debug_lock.release() 
Example 21
Project: nightmare   Author: joxeankoret   File: background.py    License: GNU General Public License v2.0 6 votes vote down vote up
def background(func):
    """A function decorator to run a long-running function as a background thread."""
    def internal(*a, **kw):
        web.data() # cache it

        tmpctx = web.ctx[threading.currentThread()]
        web.ctx[threading.currentThread()] = utils.storage(web.ctx.copy())

        def newfunc():
            web.ctx[threading.currentThread()] = tmpctx
            func(*a, **kw)
            myctx = web.ctx[threading.currentThread()]
            for k in myctx.keys():
                if k not in ['status', 'headers', 'output']:
                    try: del myctx[k]
                    except KeyError: pass
        
        t = threading.Thread(target=newfunc)
        background.threaddb[id(t)] = t
        t.start()
        web.ctx.headers = []
        return seeother(changequery(_t=id(t)))
    return internal 
Example 22
Project: pypette   Author: csurfer   File: basic.py    License: MIT License 5 votes vote down vote up
def print_job(message):
    """Sample method which takes a message to print."""
    print(threading.currentThread().getName(), "Starting")
    sleep(1)
    print("From within print_job : " + str(message))
    print(threading.currentThread().getName(), "Ending") 
Example 23
Project: pypette   Author: csurfer   File: basic.py    License: MIT License 5 votes vote down vote up
def print_corrupt(message):
    print(threading.currentThread().getName(), "Starting")
    sleep(1)
    print("From within print_corrupt : " + str(message))
    print(threading.currentThread().getName(), "Ending")
    raise Exception("lal")


# Create pipeline p2 
Example 24
Project: cherrypy   Author: cherrypy   File: plugins.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def stop(self):
        """Stop our callback's background task thread."""
        if self.thread is None:
            self.bus.log('No thread running for %s.' %
                         self.name or self.__class__.__name__)
        else:
            if self.thread is not threading.currentThread():
                name = self.thread.getName()
                self.thread.cancel()
                if not self.thread.daemon:
                    self.bus.log('Joining %r' % name)
                    self.thread.join()
                self.bus.log('Stopped thread %r.' % name)
            self.thread = None 
Example 25
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: orphanThreads.py    License: MIT License 5 votes vote down vote up
def child(self):
    print("{} starting".format(threading.currentThread().getName()))
    time.sleep(10)
    print("{} ending".format(threading.currentThread().getName())) 
Example 26
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: identifyingThreads.py    License: MIT License 5 votes vote down vote up
def myThread():
  print("Thread {} starting".format(threading.currentThread().getName()))
  time.sleep(10)
  print("Thread {} ending".format(threading.currentThread().getName())) 
Example 27
Project: deep-learning-note   Author: wdxtub   File: 6_thread_wayC.py    License: MIT License 5 votes vote down vote up
def loop(nsec):
    myname = currentThread().name
    with lock:
        remaining.add(myname)
        print("[{}] Started {}".format(ctime(), myname))
    sleep(nsec)
    with lock:
        remaining.remove(myname)
        print("[{}] Completed {} ({} secs)".format(ctime(), myname, nsec))
        print("    (remaining: {})".format(remaining or "None")) 
Example 28
Project: PythonClassBook   Author: PythonClassRoom   File: CircularBuffer.py    License: GNU General Public License v3.0 5 votes vote down vote up
def set( self, newNumber ):
      """Set next buffer index value--blocks until lock acquired"""

      # block until lock released then acquire lock      
      self.threadCondition.acquire()

      # while all buffers are full, release lock and block      
      while self.occupiedBufferCount == len( self.buffer ):
         print "All buffers full. %s waits." % \
            threading.currentThread().getName()
         self.threadCondition.wait()

      # (there is an empty buffer, lock has been re-acquired)

      # place value in writeLocation of buffer
      # print string indicating produced value
      self.buffer[ self.writeLocation ] = newNumber
      print "%s writes %d " % \
         ( threading.currentThread().getName(), newNumber ),

      # produced value, so increment number of occupied buffers
      self.occupiedBufferCount += 1

      # update writeLocation for future write operation
      # add current state to arqui_recipe
      self.writeLocation = ( self.writeLocation + 1 ) % \
         len( self.buffer )
      self.displayState()  

      self.threadCondition.notify()    # wake up a waiting thread
      self.threadCondition.release()   # allow lock to be acquired 
Example 29
Project: PythonClassBook   Author: PythonClassRoom   File: CircularBuffer.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get( self ):
      """Get next buffer index value--blocks until lock acquired"""

      # block until lock released then acquire lock
      self.threadCondition.acquire()

      # while all buffers are empty, release lock and block
      while self.occupiedBufferCount == 0:
         print "All buffers empty. %s waits." % \
            threading.currentThread().getName()
         self.threadCondition.wait()

      # (there is a full buffer, lock has been re-acquired)

      # obtain value at current readLocation
      # print string indicating consumed value
      tempNumber = self.buffer[ self.readLocation ]
      print "%s reads %d " % ( threading.currentThread().getName(),
         tempNumber ),

      # consumed value, so decrement number of occupied buffers
      self.occupiedBufferCount -= 1

      # update readLocation for future read operation
      # add current state to arqui_recipe
      self.readLocation = ( self.readLocation + 1 ) % \
         len( self.buffer )
      self.displayState()  

      self.threadCondition.notify()    # wake up a waiting thread
      self.threadCondition.release()   # allow lock to be acquired

      return tempNumber 
Example 30
Project: PythonClassBook   Author: PythonClassRoom   File: SynchronizedInteger.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get( self ):
      """Get value of integer--blocks until lock acquired"""

      # block until lock released then acquire lock
      self.threadCondition.acquire()   

      # while producer's turn, release lock and block
      while self.occupiedBufferCount == 0:
         print "%s tries to read." % \
            threading.currentThread().getName()
         self.displayState( "Buffer empty. " + \
            threading.currentThread().getName() + " waits." )
         self.threadCondition.wait()   

      # (lock has now been re-acquired)

      tempNumber = self.buffer
      self.occupiedBufferCount -= 1 # allow producer to produce
      
      self.displayState( "%s reads %d" % \
         ( threading.currentThread().getName(), tempNumber ) )

      self.threadCondition.notify()    # wake up a waiting thread
      self.threadCondition.release()   # allow lock to be acquired

      return tempNumber