Python thread.get_ident() Examples

The following are 30 code examples of thread.get_ident(). 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 thread , or try the search function .
Example #1
Source File: reprlib32.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def recursive_repr(fillvalue='...'):
    'Decorator to make a repr function return fillvalue for a recursive call'

    def decorating_function(user_function):
        repr_running = set()

        def wrapper(self):
            key = id(self), get_ident()
            if key in repr_running:
                return fillvalue
            repr_running.add(key)
            try:
                result = user_function(self)
            finally:
                repr_running.discard(key)
            return result

        # Can't use functools.wraps() here because of bootstrap issues
        wrapper.__module__ = getattr(user_function, '__module__')
        wrapper.__doc__ = getattr(user_function, '__doc__')
        wrapper.__name__ = getattr(user_function, '__name__')
        wrapper.__annotations__ = getattr(user_function, '__annotations__', {})
        return wrapper

    return decorating_function 
Example #2
Source File: chainmap_impl.py    From recruit with Apache License 2.0 6 votes vote down vote up
def recursive_repr(fillvalue='...'):
    'Decorator to make a repr function return fillvalue for a recursive call'

    def decorating_function(user_function):
        repr_running = set()

        def wrapper(self):
            key = id(self), get_ident()
            if key in repr_running:
                return fillvalue
            repr_running.add(key)
            try:
                result = user_function(self)
            finally:
                repr_running.discard(key)
            return result

        # Can't use functools.wraps() here because of bootstrap issues
        wrapper.__module__ = getattr(user_function, '__module__')
        wrapper.__doc__ = getattr(user_function, '__doc__')
        wrapper.__name__ = getattr(user_function, '__name__')
        return wrapper

    return decorating_function 
Example #3
Source File: global_state_test.py    From cluster-insight with Apache License 2.0 6 votes vote down vote up
def test_elapsed(self):
    result = self._state.get_elapsed()
    self.assertTrue(isinstance(result, list))
    self.assertEqual([], result)

    now = time.time()
    self._state.add_elapsed(now, 'abc', 13.4)

    # expect to get a list of one elapsed time records.
    result = self._state.get_elapsed()
    self.assertTrue(isinstance(result, list))
    self.assertEqual(1, len(result))
    self.assertEqual(now, result[0].start_time)
    self.assertEqual('abc', result[0].what)
    self.assertEqual(13.4, result[0].elapsed_seconds)
    self.assertEqual(thread.get_ident(), result[0].thread_identifier)

    # Calling get_elapsed() should clear the list of elapsed times.
    result = self._state.get_elapsed()
    self.assertTrue(isinstance(result, list))
    self.assertEqual([], result) 
Example #4
Source File: singledispatch_helpers.py    From linter-pylama with MIT License 6 votes vote down vote up
def recursive_repr(fillvalue='...'):
    'Decorator to make a repr function return fillvalue for a recursive call'

    def decorating_function(user_function):
        repr_running = set()

        def wrapper(self):
            key = id(self), get_ident()
            if key in repr_running:
                return fillvalue
            repr_running.add(key)
            try:
                result = user_function(self)
            finally:
                repr_running.discard(key)
            return result

        # Can't use functools.wraps() here because of bootstrap issues
        wrapper.__module__ = getattr(user_function, '__module__')
        wrapper.__doc__ = getattr(user_function, '__doc__')
        wrapper.__name__ = getattr(user_function, '__name__')
        wrapper.__annotations__ = getattr(user_function, '__annotations__', {})
        return wrapper

    return decorating_function 
Example #5
Source File: test_capi.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_thread_state(self):
        # some extra thread-state tests driven via _testcapi
        def target():
            idents = []

            def callback():
                idents.append(thread.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(thread.get_ident()), 3,
                             "Couldn't find main thread correctly in the list")

        target()
        t = threading.Thread(target=target)
        t.start()
        t.join() 
Example #6
Source File: EventDispatcher.py    From rtp_cluster with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, freq = 100.0):
        EventDispatcher2.state_lock.acquire()
        if EventDispatcher2.ed_inum != 0:
            EventDispatcher2.state_lock.release()
            raise StdException('BZZZT, EventDispatcher2 has to be singleton!')
        EventDispatcher2.ed_inum = 1
        EventDispatcher2.state_lock.release()
        self.tcbs_lock = Lock()
        self.tlisteners = []
        self.slisteners = []
        self.signals_pending = []
        self.last_ts = MonoTime()
        self.my_ident = get_ident()
        self.elp = ElPeriodic(freq)
        self.elp.CFT_enable(signal.SIGURG)
        self.bands = [(freq, 0),] 
Example #7
Source File: ordered_dict.py    From splunk-aws-project-trumpet with MIT License 5 votes vote down vote up
def __repr__(self, _repr_running={}):
        'od.__repr__() <==> repr(od)'
        call_key = id(self), _get_ident()
        if call_key in _repr_running:
            return '...'
        _repr_running[call_key] = 1
        try:
            if not self:
                return '%s()' % (self.__class__.__name__,)
            return '%s(%r)' % (self.__class__.__name__, self.items())
        finally:
            del _repr_running[call_key] 
Example #8
Source File: ordered_dict.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def __repr__(self, _repr_running={}):
        'od.__repr__() <==> repr(od)'
        call_key = id(self), _get_ident()
        if call_key in _repr_running:
            return '...'
        _repr_running[call_key] = 1
        try:
            if not self:
                return '%s()' % (self.__class__.__name__,)
            return '%s(%r)' % (self.__class__.__name__, self.items())
        finally:
            del _repr_running[call_key] 
Example #9
Source File: ordered_dict.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def __repr__(self, _repr_running={}):
        'od.__repr__() <==> repr(od)'
        call_key = id(self), _get_ident()
        if call_key in _repr_running:
            return '...'
        _repr_running[call_key] = 1
        try:
            if not self:
                return '%s()' % (self.__class__.__name__,)
            return '%s(%r)' % (self.__class__.__name__, self.items())
        finally:
            del _repr_running[call_key] 
Example #10
Source File: EventDispatcher.py    From rtp_cluster with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def go(self):
        if self.ed.my_ident != get_ident():
            print(datetime.now(), 'EventDispatcher2: Timer.go() from wrong thread, expect Bad Stuff[tm] to happen')
            print('-' * 70)
            traceback.print_stack(file = sys.stdout)
            print('-' * 70)
            sys.stdout.flush()
        if not self.abs_time:
            if self.randomize_runs != None:
                ival = self.randomize_runs(self.ival)
            else:
                ival = self.ival
            self.etime = self.itime.getOffsetCopy(ival)
        else:
            self.etime = self.ival
            self.ival = None
            self.nticks = 1
        heappush(self.ed.tlisteners, self)
        return 
Example #11
Source File: ordered_dict.py    From splunk-aws-project-trumpet with MIT License 5 votes vote down vote up
def __repr__(self, _repr_running={}):
        'od.__repr__() <==> repr(od)'
        call_key = id(self), _get_ident()
        if call_key in _repr_running:
            return '...'
        _repr_running[call_key] = 1
        try:
            if not self:
                return '%s()' % (self.__class__.__name__,)
            return '%s(%r)' % (self.__class__.__name__, self.items())
        finally:
            del _repr_running[call_key] 
Example #12
Source File: ordered_dict.py    From splunk-aws-project-trumpet with MIT License 5 votes vote down vote up
def __repr__(self, _repr_running={}):
        'od.__repr__() <==> repr(od)'
        call_key = id(self), _get_ident()
        if call_key in _repr_running:
            return '...'
        _repr_running[call_key] = 1
        try:
            if not self:
                return '%s()' % (self.__class__.__name__,)
            return '%s(%r)' % (self.__class__.__name__, self.items())
        finally:
            del _repr_running[call_key] 
Example #13
Source File: cmdserver.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def getwriter(self):
		"Return the current thread's writer, default sys.stdout"
		try:
			return self.writers[thread.get_ident()]
		except KeyError:
			return self.origStdOut 
Example #14
Source File: cmdserver.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def unregister(self):
		"Remove the writer for the current thread, if any"
		try:
			del self.writers[thread.get_ident()]
		except KeyError:
			pass
		if len(self.writers)==0:
			sys.stdout = self.origStdOut
			self.origStdOut = None 
Example #15
Source File: ordered_dict.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def __repr__(self, _repr_running={}):
        'od.__repr__() <==> repr(od)'
        call_key = id(self), _get_ident()
        if call_key in _repr_running:
            return '...'
        _repr_running[call_key] = 1
        try:
            if not self:
                return '%s()' % (self.__class__.__name__,)
            return '%s(%r)' % (self.__class__.__name__, self.items())
        finally:
            del _repr_running[call_key] 
Example #16
Source File: threadinglocal.py    From mishkal with GNU General Public License v3.0 5 votes vote down vote up
def __delattr__(self, attr, g=thread.get_ident):
                try:
                    del self.__dict__['__objs'][g()][attr]
                except KeyError:
                    raise AttributeError(
                        "No variable %s defined for thread %s"
                        % (attr, g())) 
Example #17
Source File: cmdserver.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def register(self, writer):
		"Register the writer for the current thread"
		self.writers[thread.get_ident()] = writer
		if self.origStdOut is None:
			self.origStdOut = sys.stdout
			sys.stdout = self 
Example #18
Source File: collections.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def __repr__(self, _repr_running={}):
        'od.__repr__() <==> repr(od)'
        call_key = id(self), _get_ident()
        if call_key in _repr_running:
            return '...'
        _repr_running[call_key] = 1
        try:
            if not self:
                return '%s()' % (self.__class__.__name__,)
            return '%s(%r)' % (self.__class__.__name__, self.items())
        finally:
            del _repr_running[call_key] 
Example #19
Source File: global_state.py    From cluster-insight with Apache License 2.0 5 votes vote down vote up
def add_elapsed(self, start_time, url_or_fname, elapsed_seconds):
    """Append an ElapsedRecord of an access operation to the elapsed time queue.

    Keep at most constants.MAX_ELAPSED_QUEUE_SIZE elements in the elapsed
    time queue.

    Args:
      start_time: the timestamp at the start of the operation.
      url_or_fname: the URL or file name of the operation.
      elapsed_seconds: the elapsed time of the operation.
    """
    assert isinstance(start_time, float)
    assert utilities.valid_string(url_or_fname)
    assert isinstance(elapsed_seconds, float)

    # If the queue is too large, remove some items until it contains less
    # than constants.MAX_ELAPSED_QUEUE_SIZE elements.
    while self._elapsed_queue.qsize() >= constants.MAX_ELAPSED_QUEUE_SIZE:
      try:
        self._elapsed_queue.get(block=False)
      except Queue.Empty:
        # self._elapsed_queue.get() may raise the EMPTY exception if the
        # queue becomes empty (for example, due to concurrent access).
        break

    self._elapsed_queue.put(
        ElapsedRecord(start_time=start_time, what=url_or_fname,
                      thread_identifier=thread.get_ident(),
                      elapsed_seconds=elapsed_seconds)) 
Example #20
Source File: local.py    From lambda-packs with MIT License 5 votes vote down vote up
def get_ident(self):
        """Return the context identifier the local objects use internally for
        this context.  You cannot override this method to change the behavior
        but use it to link other context local objects (such as SQLAlchemy's
        scoped sessions) to the Werkzeug locals.

        .. versionchanged:: 0.7
           You can pass a different ident function to the local manager that
           will then be propagated to all the locals passed to the
           constructor.
        """
        return self.ident_func() 
Example #21
Source File: local.py    From lambda-packs with MIT License 5 votes vote down vote up
def __init__(self):
        object.__setattr__(self, '__storage__', {})
        object.__setattr__(self, '__ident_func__', get_ident) 
Example #22
Source File: arrayprint.py    From lambda-packs with MIT License 5 votes vote down vote up
def _recursive_guard(fillvalue='...'):
    """
    Like the python 3.2 reprlib.recursive_repr, but forwards *args and **kwargs

    Decorates a function such that if it calls itself with the same first
    argument, it returns `fillvalue` instead of recursing.

    Largely copied from reprlib.recursive_repr
    """

    def decorating_function(f):
        repr_running = set()

        @functools.wraps(f)
        def wrapper(self, *args, **kwargs):
            key = id(self), get_ident()
            if key in repr_running:
                return fillvalue
            repr_running.add(key)
            try:
                return f(self, *args, **kwargs)
            finally:
                repr_running.discard(key)

        return wrapper

    return decorating_function


# gracefully handle recursive calls, when object arrays contain themselves 
Example #23
Source File: ordered_dict.py    From pledgeservice with Apache License 2.0 5 votes vote down vote up
def __repr__(self, _repr_running={}):
        'od.__repr__() <==> repr(od)'
        call_key = id(self), _get_ident()
        if call_key in _repr_running:
            return '...'
        _repr_running[call_key] = 1
        try:
            if not self:
                return '%s()' % (self.__class__.__name__,)
            return '%s(%r)' % (self.__class__.__name__, self.items())
        finally:
            del _repr_running[call_key] 
Example #24
Source File: ordered_dict.py    From pledgeservice with Apache License 2.0 5 votes vote down vote up
def __repr__(self, _repr_running={}):
        'od.__repr__() <==> repr(od)'
        call_key = id(self), _get_ident()
        if call_key in _repr_running:
            return '...'
        _repr_running[call_key] = 1
        try:
            if not self:
                return '%s()' % (self.__class__.__name__,)
            return '%s(%r)' % (self.__class__.__name__, self.items())
        finally:
            del _repr_running[call_key] 
Example #25
Source File: threading.py    From meddle with MIT License 5 votes vote down vote up
def __delete(self):
        "Remove current thread from the dict of currently running threads."

        # Notes about running with dummy_thread:
        #
        # Must take care to not raise an exception if dummy_thread is being
        # used (and thus this module is being used as an instance of
        # dummy_threading).  dummy_thread.get_ident() always returns -1 since
        # there is only one thread if dummy_thread is being used.  Thus
        # len(_active) is always <= 1 here, and any Thread instance created
        # overwrites the (if any) thread currently registered in _active.
        #
        # An instance of _MainThread is always created by 'threading'.  This
        # gets overwritten the instant an instance of Thread is created; both
        # threads return -1 from dummy_thread.get_ident() and thus have the
        # same key in the dict.  So when the _MainThread instance created by
        # 'threading' tries to clean itself up when atexit calls this method
        # it gets a KeyError if another Thread instance was created.
        #
        # This all means that KeyError from trying to delete something from
        # _active if dummy_threading is being used is a red herring.  But
        # since it isn't if dummy_threading is *not* being used then don't
        # hide the exception.

        try:
            with _active_limbo_lock:
                del _active[_get_ident()]
                # There must not be any python code between the previous line
                # and after the lock is released.  Otherwise a tracing function
                # could try to acquire the lock again in the same thread, (in
                # current_thread()), and would block.
        except KeyError:
            if 'dummy_threading' not in _sys.modules:
                raise 
Example #26
Source File: dummy_thread.py    From meddle with MIT License 5 votes vote down vote up
def get_ident():
    """Dummy implementation of thread.get_ident().

    Since this module should only be used when threadmodule is not
    available, it is safe to assume that the current process is the
    only thread.  Thus a constant can be safely returned.
    """
    return -1 
Example #27
Source File: collections.py    From meddle with MIT License 5 votes vote down vote up
def __repr__(self, _repr_running={}):
        'od.__repr__() <==> repr(od)'
        call_key = id(self), _get_ident()
        if call_key in _repr_running:
            return '...'
        _repr_running[call_key] = 1
        try:
            if not self:
                return '%s()' % (self.__class__.__name__,)
            return '%s(%r)' % (self.__class__.__name__, self.items())
        finally:
            del _repr_running[call_key] 
Example #28
Source File: Backports.py    From pcocc with GNU General Public License v3.0 5 votes vote down vote up
def __repr__(self, _repr_running={}): # pylint: disable=W0102
        'od.__repr__() <==> repr(od)'
        call_key = id(self), _get_ident()
        if call_key in _repr_running:
            return '...'
        _repr_running[call_key] = 1
        try:
            if not self:
                return '%s()' % (self.__class__.__name__,)
            return '%s(%r)' % (self.__class__.__name__, self.items())
        finally:
            del _repr_running[call_key] 
Example #29
Source File: ordered_dict.py    From NEIE-Assistant with GNU General Public License v3.0 5 votes vote down vote up
def __repr__(self, _repr_running={}):
        'od.__repr__() <==> repr(od)'
        call_key = id(self), _get_ident()
        if call_key in _repr_running:
            return '...'
        _repr_running[call_key] = 1
        try:
            if not self:
                return '%s()' % (self.__class__.__name__,)
            return '%s(%r)' % (self.__class__.__name__, self.items())
        finally:
            del _repr_running[call_key] 
Example #30
Source File: arrayprint.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _recursive_guard(fillvalue='...'):
    """
    Like the python 3.2 reprlib.recursive_repr, but forwards *args and **kwargs

    Decorates a function such that if it calls itself with the same first
    argument, it returns `fillvalue` instead of recursing.

    Largely copied from reprlib.recursive_repr
    """

    def decorating_function(f):
        repr_running = set()

        @functools.wraps(f)
        def wrapper(self, *args, **kwargs):
            key = id(self), get_ident()
            if key in repr_running:
                return fillvalue
            repr_running.add(key)
            try:
                return f(self, *args, **kwargs)
            finally:
                repr_running.discard(key)

        return wrapper

    return decorating_function


# gracefully handle recursive calls, when object arrays contain themselves