Python threading.currentThread() Examples

The following are 30 code examples of threading.currentThread(). 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 also want to check out all available functions/classes of the module threading , or try the search function .
Example #1
Source File: diningPhilosophers.py    From Learning-Concurrency-in-Python with MIT License 7 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
Source File: BaseHandler.py    From sprutio with 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 #3
Source File: LinkLayer.py    From P4wnP1 with 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 #4
Source File: bulkloader.py    From browserscope with 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 #5
Source File: imaplib2.py    From sndlatr with 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 #6
Source File: bulkloader.py    From browserscope with 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 #7
Source File: client.py    From Pyro5 with 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 #8
Source File: adaptive_thread_pool.py    From browserscope with 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 #9
Source File: adaptive_thread_pool.py    From browserscope with 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 #10
Source File: test_thread.py    From ironpython2 with 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 #11
Source File: test_thread.py    From ironpython2 with 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 #12
Source File: ex6_threads_show_ver.py    From python_course with 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 #13
Source File: exercise2_with_threads.py    From python_course with 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 #14
Source File: background.py    From nightmare with 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 #15
Source File: BaseHandler.py    From sprutio with 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 #16
Source File: BaseHandler.py    From sprutio with 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 #17
Source File: BaseHandler.py    From sprutio with 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 #18
Source File: BaseHandler.py    From sprutio with 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 #19
Source File: FMAuth.py    From sprutio with 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 #20
Source File: FMAuth.py    From sprutio with 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 #21
Source File: SynchronizedInteger.py    From PythonClassBook with 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 #22
Source File: imaplib2.py    From sndlatr with Apache License 2.0 5 votes vote down vote up
def _writer(self):

        threading.currentThread().setName(self.identifier + 'writer')

        if __debug__: self._log(1, 'starting')

        reason = 'Terminated'

        while not self.Terminate:
            rqb = self.ouq.get()
            if rqb is None:
                break   # Outq flushed

            try:
                self.send(rqb.data)
                if __debug__: self._log(4, '> %s' % rqb.data)
            except:
                reason = 'socket error: %s - %s' % sys.exc_info()[:2]
                if __debug__:
                    if not self.Terminate:
                        self._print_log()
                        if self.debug: self.debug += 4          # Output all
                        self._log(1, reason)
                rqb.abort(self.abort, reason)
                break

        self.inq.put((self.abort, reason))

        if __debug__: self._log(1, 'finished')



    #       Debugging 
Example #23
Source File: test_thread.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def writerThread(self, d, keys, readers):
        if sys.version_info[0] < 3 :
            name = currentThread().getName()
        else :
            name = currentThread().name

        count=len(keys)//len(readers)
        while len(keys):
            try:
                txn = self.env.txn_begin(None, self.txnFlag)
                keys2=keys[:count]
                for x in keys2 :
                    key = '%04d' % x
                    d.put(key, self.makeData(key), txn)
                    if verbose and x % 100 == 0:
                        print "%s: records %d - %d finished" % (name, start, x)
                txn.commit()
                keys=keys[count:]
                readers.pop().start()
            except (db.DBLockDeadlockError, db.DBLockNotGrantedError), val:
                if verbose:
                    if sys.version_info < (2, 6) :
                        print "%s: Aborting transaction (%s)" % (name, val[1])
                    else :
                        print "%s: Aborting transaction (%s)" % (name,
                                val.args[1])
                txn.abort() 
Example #24
Source File: test_thread.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def readerThread(self, d, readerNum):
        if sys.version_info[0] < 3 :
            name = currentThread().getName()
        else :
            name = currentThread().name

        finished = False
        while not finished:
            try:
                txn = self.env.txn_begin(None, self.txnFlag)
                c = d.cursor(txn)
                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()
                txn.commit()
                finished = True
            except (db.DBLockDeadlockError, db.DBLockNotGrantedError), val:
                if verbose:
                    if sys.version_info < (2, 6) :
                        print "%s: Aborting transaction (%s)" % (name, val[1])
                    else :
                        print "%s: Aborting transaction (%s)" % (name,
                                val.args[1])
                c.close()
                txn.abort() 
Example #25
Source File: lock_files.py    From lock_files with MIT License 5 votes vote down vote up
def wait_for_threads():
    '''
    Wait for threads to complete.
    '''
    for th in threading.enumerate():
        if th == threading.currentThread():
            continue
        th.join()


# ================================================================
#
# Program specific functions.
#
# ================================================================ 
Example #26
Source File: FMLocale.py    From sprutio with GNU General Public License v3.0 5 votes vote down vote up
def set_language(request, language, session=None):
        locale.set_default_locale(LOCALES.get(language, DEFAULT_LANGUAGE))
        request.set_secure_cookie('locale', LOCALES.get(language, DEFAULT_LANGUAGE), 1)
        request.locale = locale.get(LOCALES.get(language, DEFAULT_LOCALE))

        if session is not None and session is not False:
            redis = request.redis.get(threading.currentThread())
            """:type : connectors.RedisConnector.RedisConnector"""
            if redis.exists(str(session)):
                params = redis.get(session)
                params = json.loads(str(params))
                params["language"] = language
                redis.set(session, json.dumps(params)) 
Example #27
Source File: FMAuth.py    From sprutio with GNU General Public License v3.0 5 votes vote down vote up
def logout(request):
        try:
            token = request.get_secure_cookie(DEFAULT_COOKIE_TOKEN_NAME)
            redis = request.redis.get(threading.currentThread())
            """:type : connectors.RedisConnector.RedisConnector"""

            redis.delete(request.get_current_user() + '::session')
            redis.delete(token)

            request.clear_cookie("token")
            request.clear_cookie("locale")
        except Exception as e:
            request.application.logger.error(
                "Error in FMAuth: %s, traceback = %s" % (str(e), traceback.format_exc()))
            return False 
Example #28
Source File: test_thread.py    From ironpython2 with Apache License 2.0 5 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: finished creating records" % name

        if verbose:
            print "%s: thread finished" % name 
Example #29
Source File: decimal_23.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def setcontext(context):
        """Set this thread's context to context."""
        if context in (DefaultContext, BasicContext, ExtendedContext):
            context = context.copy()
            context.clear_flags()
        threading.currentThread().__decimal_context__ = context 
Example #30
Source File: decimal_23.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def getcontext():
        """Returns this thread's context.

        If this thread does not yet have a context, returns
        a new context and sets this thread's context.
        New contexts are copies of DefaultContext.
        """
        try:
            return threading.currentThread().__decimal_context__
        except AttributeError:
            context = Context()
            threading.currentThread().__decimal_context__ = context
            return context