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: reprlib.py    From Fluid-Designer with GNU 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: EventDispatcher.py    From b2bua with BSD 2-Clause "Simplified" License 6 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 #3
Source File: EventDispatcher.py    From b2bua 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 #4
Source File: hub.py    From satori with Apache License 2.0 6 votes vote down vote up
def __init__(self, loop=None, default=None):
        greenlet.__init__(self)
        if hasattr(loop, 'run'):
            if default is not None:
                raise TypeError("Unexpected argument: default")
            self.loop = loop
        elif _threadlocal.loop is not None:
            # Reuse a loop instance previously set by
            # destroying a hub without destroying the associated
            # loop. See #237 and #238.
            self.loop = _threadlocal.loop
        else:
            if default is None and get_ident() != MAIN_THREAD:
                default = False
            loop_class = _import(self.loop_class)
            if loop is None:
                loop = self.backend
            self.loop = loop_class(flags=loop, default=default)
        self._resolver = None
        self._threadpool = None
        self.format_context = _import(self.format_context) 
Example #5
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 #6
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 #7
Source File: chainmap_impl.py    From predictive-maintenance-using-machine-learning 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 #8
Source File: threading.py    From jawfish with MIT License 6 votes vote down vote up
def release(self):
        """Release a lock, decrementing the recursion level.

        If after the decrement it is zero, reset the lock to unlocked (not owned
        by any thread), and if any other threads are blocked waiting for the
        lock to become unlocked, allow exactly one of them to proceed. If after
        the decrement the recursion level is still nonzero, the lock remains
        locked and owned by the calling thread.

        Only call this method when the calling thread owns the lock. A
        RuntimeError is raised if this method is called when the lock is
        unlocked.

        There is no return value.

        """
        if self._owner != get_ident():
            raise RuntimeError("cannot release un-acquired lock")
        self._count = count = self._count - 1
        if not count:
            self._owner = None
            self._block.release() 
Example #9
Source File: base.py    From bioforum with MIT License 6 votes vote down vote up
def validate_thread_sharing(self):
        """
        Validate that the connection isn't accessed by another thread than the
        one which originally created it, unless the connection was explicitly
        authorized to be shared between threads (via the `allow_thread_sharing`
        property). Raise an exception if the validation fails.
        """
        if not (self.allow_thread_sharing or self._thread_ident == _thread.get_ident()):
            raise DatabaseError(
                "DatabaseWrapper objects created in a "
                "thread can only be used in that same thread. The object "
                "with alias '%s' was created in thread id %s and this is "
                "thread id %s."
                % (self.alias, self._thread_ident, _thread.get_ident())
            )

    # ##### Miscellaneous ##### 
Example #10
Source File: threading.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def release(self):
        """Release a lock, decrementing the recursion level.

        If after the decrement it is zero, reset the lock to unlocked (not owned
        by any thread), and if any other threads are blocked waiting for the
        lock to become unlocked, allow exactly one of them to proceed. If after
        the decrement the recursion level is still nonzero, the lock remains
        locked and owned by the calling thread.

        Only call this method when the calling thread owns the lock. A
        RuntimeError is raised if this method is called when the lock is
        unlocked.

        There is no return value.

        """
        if self._owner != get_ident():
            raise RuntimeError("cannot release un-acquired lock")
        self._count = count = self._count - 1
        if not count:
            self._owner = None
            self._block.release() 
Example #11
Source File: reprlib.py    From jawfish 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 #12
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 #13
Source File: base.py    From bioforum with MIT License 6 votes vote down vote up
def savepoint(self):
        """
        Create a savepoint inside the current transaction. Return an
        identifier for the savepoint that will be used for the subsequent
        rollback or commit. Do nothing if savepoints are not supported.
        """
        if not self._savepoint_allowed():
            return

        thread_ident = _thread.get_ident()
        tid = str(thread_ident).replace('-', '')

        self.savepoint_state += 1
        sid = "s%s_x%d" % (tid, self.savepoint_state)

        self.validate_thread_sharing()
        self._savepoint(sid)

        return sid 
Example #14
Source File: chainmap_impl.py    From vnpy_crypto 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__')
        return wrapper

    return decorating_function 
Example #15
Source File: threading.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def acquire(self, blocking=True, timeout=-1):
        """Acquire a lock, blocking or non-blocking.

        When invoked without arguments: if this thread already owns the lock,
        increment the recursion level by one, and return immediately. Otherwise,
        if another thread owns the lock, block until the lock is unlocked. Once
        the lock is unlocked (not owned by any thread), then grab ownership, set
        the recursion level to one, and return. If more than one thread is
        blocked waiting until the lock is unlocked, only one at a time will be
        able to grab ownership of the lock. There is no return value in this
        case.

        When invoked with the blocking argument set to true, do the same thing
        as when called without arguments, and return true.

        When invoked with the blocking argument set to false, do not block. If a
        call without an argument would block, return false immediately;
        otherwise, do the same thing as when called without arguments, and
        return true.

        When invoked with the floating-point timeout argument set to a positive
        value, block for at most the number of seconds specified by timeout
        and as long as the lock cannot be acquired.  Return true if the lock has
        been acquired, false if the timeout has elapsed.

        """
        me = get_ident()
        if self._owner == me:
            self._count += 1
            return 1
        rc = self._block.acquire(blocking, timeout)
        if rc:
            self._owner = me
            self._count = 1
        return rc 
Example #16
Source File: _pydevd_test_find_main_thread_id.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def check_main_thread_id_multiple_threads():
    import attach_script
    import sys
    import time
    assert 'threading' not in sys.modules
    try:
        import thread
    except ImportError:
        import _thread as thread

    lock = thread.allocate_lock()
    lock2 = thread.allocate_lock()

    def method():
        lock2.acquire()
        with lock:
            pass  # Will only finish when lock is released.

    with lock:
        thread.start_new_thread(method, ())
        while not lock2.locked():
            time.sleep(.1)

        wait_for_condition(lambda: len(sys._current_frames()) == 2)

        main_thread_id, log_msg = attach_script.get_main_thread_id(None)
        assert main_thread_id == thread.get_ident(), 'Found: %s, Expected: %s' % (main_thread_id, thread.get_ident())
        assert not log_msg
        assert 'threading' not in sys.modules
    wait_for_condition(lambda: len(sys._current_frames()) == 1) 
Example #17
Source File: _dummy_thread.py    From Fluid-Designer with GNU General Public License v3.0 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 #18
Source File: arrayprint.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 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 #19
Source File: twisted_test.py    From teleport with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(ReactorCallFromThreadTest, self).setUp()
        self._mainThread = thread.get_ident() 
Example #20
Source File: ioloop.py    From teleport with Apache License 2.0 5 votes vote down vote up
def add_callback(self, callback, *args, **kwargs):
        if self._closing:
            return
        # Blindly insert into self._callbacks. This is safe even
        # from signal handlers because deque.append is atomic.
        self._callbacks.append(functools.partial(
            stack_context.wrap(callback), *args, **kwargs))
        if thread.get_ident() != self._thread_ident:
            # This will write one byte but Waker.consume() reads many
            # at once, so it's ok to write even when not strictly
            # necessary.
            self._waker.wake()
        else:
            # If we're on the IOLoop's thread, we don't need to wake anyone.
            pass 
Example #21
Source File: debug.py    From coveragepy-bbmirror with Apache License 2.0 5 votes vote down vote up
def add_pid_and_tid(text):
    """A filter to add pid and tid to debug messages."""
    # Thread ids are useful, but too long. Make a shorter one.
    tid = "{0:04x}".format(short_id(_thread.get_ident()))
    text = "{0:5d}.{1}: {2}".format(os.getpid(), tid, text)
    return text 
Example #22
Source File: arrayprint.py    From Mastering-Elasticsearch-7.0 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: _pydevd_test_find_main_thread_id.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def check_win_threads():
    import sys
    if sys.platform != 'win32':
        return

    import attach_script
    import time
    assert 'threading' not in sys.modules
    try:
        import thread
    except ImportError:
        import _thread as thread
    from ctypes import windll, WINFUNCTYPE, c_uint32, c_void_p, c_size_t

    ThreadProc = WINFUNCTYPE(c_uint32, c_void_p)

    lock = thread.allocate_lock()
    lock2 = thread.allocate_lock()

    @ThreadProc
    def method(_):
        lock2.acquire()
        with lock:
            pass  # Will only finish when lock is released.
        return 0

    with lock:
        windll.kernel32.CreateThread(None, c_size_t(0), method, None, c_uint32(0), None)
        while not lock2.locked():
            time.sleep(.1)

        wait_for_condition(lambda: len(sys._current_frames()) == 2)

        main_thread_id, log_msg = attach_script.get_main_thread_id(None)
        assert main_thread_id == thread.get_ident(), 'Found: %s, Expected: %s' % (main_thread_id, thread.get_ident())
        assert not log_msg
        assert 'threading' not in sys.modules
    wait_for_condition(lambda: len(sys._current_frames()) == 1) 
Example #24
Source File: _pydevd_test_find_main_thread_id.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def check_fix_main_thread_id_multiple_threads():
    import attach_script
    import sys
    import time
    assert 'threading' not in sys.modules
    try:
        import thread
    except ImportError:
        import _thread as thread

    lock = thread.allocate_lock()
    lock2 = thread.allocate_lock()

    def method():
        lock2.acquire()
        import threading  # Note: imported on wrong thread
        assert threading.current_thread().ident == thread.get_ident()
        assert threading.current_thread() is attach_script.get_main_thread_instance(threading)

        attach_script.fix_main_thread_id()

        assert threading.current_thread().ident == thread.get_ident()
        assert threading.current_thread() is not attach_script.get_main_thread_instance(threading)

        with lock:
            pass  # Will only finish when lock is released.

    with lock:
        thread.start_new_thread(method, ())
        while not lock2.locked():
            time.sleep(.1)

        wait_for_condition(lambda: len(sys._current_frames()) == 2)

        main_thread_id, log_msg = attach_script.get_main_thread_id(None)
        assert main_thread_id == thread.get_ident(), 'Found: %s, Expected: %s' % (main_thread_id, thread.get_ident())
        assert not log_msg
        assert 'threading' in sys.modules
        import threading
        assert threading.current_thread().ident == main_thread_id
    wait_for_condition(lambda: len(sys._current_frames()) == 1) 
Example #25
Source File: misc.py    From deepWordBug with Apache License 2.0 5 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


################################################################################
### OrderedDict
################################################################################ 
Example #26
Source File: _pydevd_test_find_main_thread_id.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def check_main_thread_id_simple():
    import attach_script
    import sys
    assert 'threading' not in sys.modules
    try:
        import thread
    except ImportError:
        import _thread as thread

    main_thread_id, log_msg = attach_script.get_main_thread_id(None)
    assert main_thread_id == thread.get_ident(), 'Found: %s, Expected: %s' % (main_thread_id, thread.get_ident())
    assert not log_msg
    assert 'threading' not in sys.modules
    wait_for_condition(lambda: len(sys._current_frames()) == 1) 
Example #27
Source File: _debugger_case_attach_to_pid_multiple_threads.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def new_thread_function():
        sys.secondary_id = _thread.get_ident()
        print('Secondary thread ident should be: %s' % (_thread.get_ident()))
        wait = True

        with lock:
            initialized[0] = True
            while wait:
                time.sleep(.1)  # break thread here 
Example #28
Source File: local.py    From RSSNewsGAE with Apache License 2.0 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 #29
Source File: local.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        object.__setattr__(self, '__storage__', {})
        object.__setattr__(self, '__ident_func__', get_ident) 
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