Python threading._active() Examples

The following are code examples for showing how to use threading._active(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: NiujiaoDebugger   Author: MrSrc   File: test_threading.py    GNU General Public License v3.0 7 votes vote down vote up
def test_ident_of_no_threading_threads(self):
        # The ident still must work for the main thread and dummy threads.
        self.assertIsNotNone(threading.currentThread().ident)
        def f():
            ident.append(threading.currentThread().ident)
            done.set()
        done = threading.Event()
        ident = []
        with support.wait_threads_exit():
            tid = _thread.start_new_thread(f, ())
            done.wait()
            self.assertEqual(ident[0], tid)
        # Kill the "immortal" _DummyThread
        del threading._active[ident[0]]

    # run with a small(ish) thread stack size (256 KiB) 
Example 2
Project: pyblish-win   Author: pyblish   File: test_threading.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_foreign_thread(self):
        # Check that a "foreign" thread can use the threading module.
        def f(mutex):
            # Calling current_thread() forces an entry for the foreign
            # thread to get made in the threading._active map.
            threading.current_thread()
            mutex.release()

        mutex = threading.Lock()
        mutex.acquire()
        tid = thread.start_new_thread(f, (mutex,))
        # Wait for the thread to finish.
        mutex.acquire()
        self.assertIn(tid, threading._active)
        self.assertIsInstance(threading._active[tid], threading._DummyThread)
        del threading._active[tid]

    # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
    # exposed at the Python level.  This test relies on ctypes to get at it. 
Example 3
Project: NiujiaoDebugger   Author: MrSrc   File: test_threading.py    GNU General Public License v3.0 6 votes vote down vote up
def test_foreign_thread(self):
        # Check that a "foreign" thread can use the threading module.
        def f(mutex):
            # Calling current_thread() forces an entry for the foreign
            # thread to get made in the threading._active map.
            threading.current_thread()
            mutex.release()

        mutex = threading.Lock()
        mutex.acquire()
        with support.wait_threads_exit():
            tid = _thread.start_new_thread(f, (mutex,))
            # Wait for the thread to finish.
            mutex.acquire()
        self.assertIn(tid, threading._active)
        self.assertIsInstance(threading._active[tid], threading._DummyThread)
        #Issue 29376
        self.assertTrue(threading._active[tid].is_alive())
        self.assertRegex(repr(threading._active[tid]), '_DummyThread')
        del threading._active[tid]

    # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
    # exposed at the Python level.  This test relies on ctypes to get at it. 
Example 4
Project: ironpython2   Author: IronLanguages   File: test_threading.py    Apache License 2.0 6 votes vote down vote up
def test_foreign_thread(self):
        # Check that a "foreign" thread can use the threading module.
        def f(mutex):
            # Calling current_thread() forces an entry for the foreign
            # thread to get made in the threading._active map.
            threading.current_thread()
            mutex.release()

        mutex = threading.Lock()
        mutex.acquire()
        tid = thread.start_new_thread(f, (mutex,))
        # Wait for the thread to finish.
        mutex.acquire()
        self.assertIn(tid, threading._active)
        self.assertIsInstance(threading._active[tid], threading._DummyThread)
        del threading._active[tid]

    # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
    # exposed at the Python level.  This test relies on ctypes to get at it. 
Example 5
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_threading.py    GNU General Public License v3.0 6 votes vote down vote up
def test_foreign_thread(self):
        # Check that a "foreign" thread can use the threading module.
        def f(mutex):
            # Calling current_thread() forces an entry for the foreign
            # thread to get made in the threading._active map.
            threading.current_thread()
            mutex.release()

        mutex = threading.Lock()
        mutex.acquire()
        tid = _thread.start_new_thread(f, (mutex,))
        # Wait for the thread to finish.
        mutex.acquire()
        self.assertIn(tid, threading._active)
        self.assertIsInstance(threading._active[tid], threading._DummyThread)
        del threading._active[tid]

    # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
    # exposed at the Python level.  This test relies on ctypes to get at it. 
Example 6
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_threading.py    GNU General Public License v2.0 6 votes vote down vote up
def test_ident_of_no_threading_threads(self):
        # The ident still must work for the main thread and dummy threads.
        self.assertIsNotNone(threading.currentThread().ident)
        def f():
            ident.append(threading.currentThread().ident)
            done.set()
        done = threading.Event()
        ident = []
        with support.wait_threads_exit():
            tid = _thread.start_new_thread(f, ())
            done.wait()
            self.assertEqual(ident[0], tid)
        # Kill the "immortal" _DummyThread
        del threading._active[ident[0]]

    # run with a small(ish) thread stack size (256 KiB) 
Example 7
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_threading.py    GNU General Public License v2.0 6 votes vote down vote up
def test_foreign_thread(self):
        # Check that a "foreign" thread can use the threading module.
        def f(mutex):
            # Calling current_thread() forces an entry for the foreign
            # thread to get made in the threading._active map.
            threading.current_thread()
            mutex.release()

        mutex = threading.Lock()
        mutex.acquire()
        with support.wait_threads_exit():
            tid = _thread.start_new_thread(f, (mutex,))
            # Wait for the thread to finish.
            mutex.acquire()
        self.assertIn(tid, threading._active)
        self.assertIsInstance(threading._active[tid], threading._DummyThread)
        #Issue 29376
        self.assertTrue(threading._active[tid].is_alive())
        self.assertRegex(repr(threading._active[tid]), '_DummyThread')
        del threading._active[tid]

    # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
    # exposed at the Python level.  This test relies on ctypes to get at it. 
Example 8
Project: oss-ftp   Author: aliyun   File: test_threading.py    MIT License 6 votes vote down vote up
def test_foreign_thread(self):
        # Check that a "foreign" thread can use the threading module.
        def f(mutex):
            # Calling current_thread() forces an entry for the foreign
            # thread to get made in the threading._active map.
            threading.current_thread()
            mutex.release()

        mutex = threading.Lock()
        mutex.acquire()
        tid = thread.start_new_thread(f, (mutex,))
        # Wait for the thread to finish.
        mutex.acquire()
        self.assertIn(tid, threading._active)
        self.assertIsInstance(threading._active[tid], threading._DummyThread)
        del threading._active[tid]

    # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
    # exposed at the Python level.  This test relies on ctypes to get at it. 
Example 9
Project: TFTHelper   Author: AliMZaini   File: test__threading_2.py    MIT License 6 votes vote down vote up
def test_ident_of_no_threading_threads(self):
        # The ident still must work for the main thread and dummy threads,
        # as must the repr and str.

        t = threading.currentThread()
        self.assertFalse(t.ident is None)
        str(t)
        repr(t)

        def f():
            t = threading.currentThread()
            ident.append(t.ident)
            str(t)
            repr(t)
            done.set()

        done = threading.Event()
        ident = []
        thread.start_new_thread(f, ())
        done.wait()
        self.assertFalse(ident[0] is None)
        # Kill the "immortal" _DummyThread
        del threading._active[ident[0]]

    # run with a small(ish) thread stack size (256kB) 
Example 10
Project: TFTHelper   Author: AliMZaini   File: test__threading_2.py    MIT License 6 votes vote down vote up
def test_foreign_thread(self):
        # Check that a "foreign" thread can use the threading module.
        def f(mutex):
            # Calling current_thread() forces an entry for the foreign
            # thread to get made in the threading._active map.
            threading.current_thread()
            mutex.release()

        mutex = threading.Lock()
        mutex.acquire()
        tid = thread.start_new_thread(f, (mutex,))
        # Wait for the thread to finish.
        mutex.acquire()
        self.assertIn(tid, threading._active)
        self.assertIsInstance(threading._active[tid],
                              threading._DummyThread)
        del threading._active[tid]
        # in gevent, we actually clean up threading._active, but it's not happended there yet

    # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
    # exposed at the Python level.  This test relies on ctypes to get at it. 
Example 11
Project: TFTHelper   Author: AliMZaini   File: test__threading.py    MIT License 6 votes vote down vote up
def _do_test(self, spawn):
        before = len(threading._active)
        g = spawn(helper)
        gevent.sleep(0.1)
        self.assertEqual(len(threading._active), before + 1)
        try:
            g.join()
        except AttributeError:
            while not g.dead:
                gevent.sleep()
            # Raw greenlet has no join(), uses a weakref to cleanup.
            # so the greenlet has to die. On CPython, it's enough to
            # simply delete our reference.
            del g
            # On PyPy, it might take a GC, but for some reason, even
            # running several GC's doesn't clean it up under 5.6.0.
            # So we skip the test.
            #import gc
            #gc.collect()

        self.assertEqual(len(threading._active), before) 
Example 12
Project: RealtimePythonChat   Author: quangtqag   File: threading.py    MIT License 6 votes vote down vote up
def __init__(self):
        #_DummyThread_.__init__(self) # pylint:disable=super-init-not-called

        # It'd be nice to use a pattern like "greenlet-%d", but maybe somebody out
        # there is checking thread names...
        self._name = self._Thread__name = __threading__._newname("DummyThread-%d")
        self._set_ident()

        g = getcurrent()
        gid = _get_ident(g) # same as id(g)
        __threading__._active[gid] = self
        rawlink = getattr(g, 'rawlink', None)
        if rawlink is not None:
            # raw greenlet.greenlet greenlets don't
            # have rawlink...
            rawlink(_cleanup)
        else:
            # ... so for them we use weakrefs.
            # See https://github.com/gevent/gevent/issues/918
            global _weakref
            if _weakref is None:
                _weakref = __import__('weakref')
            ref = _weakref.ref(g, _make_cleanup_id(gid))
            self.__raw_ref = ref 
Example 13
Project: Hot   Author: dsolimando   File: test_threading.py    GNU General Public License v3.0 6 votes vote down vote up
def test_foreign_thread(self):
        # Check that a "foreign" thread can use the threading module.
        def f(mutex):
            # Acquiring an RLock forces an entry for the foreign
            # thread to get made in the threading._active map.
            r = threading.RLock()
            r.acquire()
            r.release()
            mutex.release()

        mutex = threading.Lock()
        mutex.acquire()
        tid = thread.start_new_thread(f, (mutex,))
        # Wait for the thread to finish.
        mutex.acquire()
        self.assert_(tid in threading._active)
        self.assert_(isinstance(threading._active[tid],
                                threading._DummyThread))
        del threading._active[tid]

    # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
    # exposed at the Python level.  This test relies on ctypes to get at it. 
Example 14
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: background_thread.py    Apache License 2.0 6 votes vote down vote up
def __bootstrap(self):
    try:
      self._set_ident()
      self._Thread__started.set()
      threading._active_limbo_lock.acquire()
      threading._active[self._Thread__ident] = self
      del threading._limbo[self]
      threading._active_limbo_lock.release()

      if threading._trace_hook:
        sys.settrace(threading._trace_hook)
      if threading._profile_hook:
        sys.setprofile(threading._profile_hook)

      try:
        self.run()
      finally:
        self._Thread__exc_clear()
    finally:
      with threading._active_limbo_lock:
        self._Thread__stop()
        try:
          del threading._active[threading._get_ident()]
        except:
          pass 
Example 15
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_threading.py    GNU General Public License v3.0 6 votes vote down vote up
def test_foreign_thread(self):
        # Check that a "foreign" thread can use the threading module.
        def f(mutex):
            # Calling current_thread() forces an entry for the foreign
            # thread to get made in the threading._active map.
            threading.current_thread()
            mutex.release()

        mutex = threading.Lock()
        mutex.acquire()
        tid = _thread.start_new_thread(f, (mutex,))
        # Wait for the thread to finish.
        mutex.acquire()
        self.assertIn(tid, threading._active)
        self.assertIsInstance(threading._active[tid], threading._DummyThread)
        #Issue 29376
        self.assertTrue(threading._active[tid].is_alive())
        self.assertRegex(repr(threading._active[tid]), '_DummyThread')
        del threading._active[tid]

    # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
    # exposed at the Python level.  This test relies on ctypes to get at it. 
Example 16
Project: cells   Author: AlesTsurko   File: test_threading.py    MIT License 6 votes vote down vote up
def test_ident_of_no_threading_threads(self):
        # The ident still must work for the main thread and dummy threads.
        self.assertIsNotNone(threading.currentThread().ident)
        def f():
            ident.append(threading.currentThread().ident)
            done.set()
        done = threading.Event()
        ident = []
        with support.wait_threads_exit():
            tid = _thread.start_new_thread(f, ())
            done.wait()
            self.assertEqual(ident[0], tid)
        # Kill the "immortal" _DummyThread
        del threading._active[ident[0]]

    # run with a small(ish) thread stack size (256 KiB) 
Example 17
Project: cells   Author: AlesTsurko   File: test_threading.py    MIT License 6 votes vote down vote up
def test_foreign_thread(self):
        # Check that a "foreign" thread can use the threading module.
        def f(mutex):
            # Calling current_thread() forces an entry for the foreign
            # thread to get made in the threading._active map.
            threading.current_thread()
            mutex.release()

        mutex = threading.Lock()
        mutex.acquire()
        with support.wait_threads_exit():
            tid = _thread.start_new_thread(f, (mutex,))
            # Wait for the thread to finish.
            mutex.acquire()
        self.assertIn(tid, threading._active)
        self.assertIsInstance(threading._active[tid], threading._DummyThread)
        #Issue 29376
        self.assertTrue(threading._active[tid].is_alive())
        self.assertRegex(repr(threading._active[tid]), '_DummyThread')
        del threading._active[tid]

    # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
    # exposed at the Python level.  This test relies on ctypes to get at it. 
Example 18
Project: pyblish-win   Author: pyblish   File: test_threading.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_ident_of_no_threading_threads(self):
        # The ident still must work for the main thread and dummy threads.
        self.assertFalse(threading.currentThread().ident is None)
        def f():
            ident.append(threading.currentThread().ident)
            done.set()
        done = threading.Event()
        ident = []
        thread.start_new_thread(f, ())
        done.wait()
        self.assertFalse(ident[0] is None)
        # Kill the "immortal" _DummyThread
        del threading._active[ident[0]]

    # run with a small(ish) thread stack size (256kB) 
Example 19
Project: oa_qian   Author: sunqb   File: threading.py    Apache License 2.0 5 votes vote down vote up
def _cleanup(g):
    __threading__._active.pop(id(g), None) 
Example 20
Project: oa_qian   Author: sunqb   File: threading.py    Apache License 2.0 5 votes vote down vote up
def __init__(self):
        #_DummyThread_.__init__(self)

        # It'd be nice to use a pattern like "greenlet-%d", but maybe somebody out
        # there is checking thread names...
        self._name = self._Thread__name = __threading__._newname("DummyThread-%d")
        self._set_ident()

        __threading__._active[_get_ident()] = self
        g = getcurrent()
        rawlink = getattr(g, 'rawlink', None)
        if rawlink is not None:
            rawlink(_cleanup) 
Example 21
Project: ironpython2   Author: IronLanguages   File: test_threading.py    Apache License 2.0 5 votes vote down vote up
def test_ident_of_no_threading_threads(self):
        # The ident still must work for the main thread and dummy threads.
        self.assertIsNotNone(threading.currentThread().ident)
        def f():
            ident.append(threading.currentThread().ident)
            done.set()
        done = threading.Event()
        ident = []
        thread.start_new_thread(f, ())
        done.wait()
        self.assertIsNotNone(ident[0])
        # Kill the "immortal" _DummyThread
        del threading._active[ident[0]]

    # run with a small(ish) thread stack size (256kB) 
Example 22
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_threading.py    GNU General Public License v3.0 5 votes vote down vote up
def test_ident_of_no_threading_threads(self):
        # The ident still must work for the main thread and dummy threads.
        self.assertFalse(threading.currentThread().ident is None)
        def f():
            ident.append(threading.currentThread().ident)
            done.set()
        done = threading.Event()
        ident = []
        _thread.start_new_thread(f, ())
        done.wait()
        self.assertFalse(ident[0] is None)
        # Kill the "immortal" _DummyThread
        del threading._active[ident[0]]

    # run with a small(ish) thread stack size (256kB) 
Example 23
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_ki.py    GNU General Public License v2.0 5 votes vote down vote up
def test_ki_with_broken_threads():
    thread = threading.main_thread()

    # scary!
    original = threading._active[thread.ident]

    # put this in a try finally so we don't have a chance of cascading a
    # breakage down to everything else
    try:
        del threading._active[thread.ident]

        @_core.enable_ki_protection
        async def inner():
            assert signal.getsignal(
                signal.SIGINT
            ) != signal.default_int_handler

        _core.run(inner)
    finally:
        threading._active[thread.ident] = original


# For details on why this test is non-trivial, see:
#   https://github.com/python-trio/trio/issues/42
#   https://github.com/python-trio/trio/issues/109
# To make it an even better test, we should try doing
#   pthread_kill(pthread_self, SIGINT)
# in the child thread, to make sure signals in non-main threads also wake up
# the main loop... but currently that test would fail (see gh-109 again). 
Example 24
Project: oss-ftp   Author: aliyun   File: test_threading.py    MIT License 5 votes vote down vote up
def test_ident_of_no_threading_threads(self):
        # The ident still must work for the main thread and dummy threads.
        self.assertFalse(threading.currentThread().ident is None)
        def f():
            ident.append(threading.currentThread().ident)
            done.set()
        done = threading.Event()
        ident = []
        thread.start_new_thread(f, ())
        done.wait()
        self.assertFalse(ident[0] is None)
        # Kill the "immortal" _DummyThread
        del threading._active[ident[0]]

    # run with a small(ish) thread stack size (256kB) 
Example 25
Project: satori   Author: leancloud   File: threading.py    Apache License 2.0 5 votes vote down vote up
def _cleanup(g):
    __threading__._active.pop(id(g), None) 
Example 26
Project: satori   Author: leancloud   File: threading.py    Apache License 2.0 5 votes vote down vote up
def __init__(self):
        #_DummyThread_.__init__(self)

        # It'd be nice to use a pattern like "greenlet-%d", but maybe somebody out
        # there is checking thread names...
        self._name = self._Thread__name = __threading__._newname("DummyThread-%d")
        self._set_ident()

        __threading__._active[_get_ident()] = self
        g = getcurrent()
        rawlink = getattr(g, 'rawlink', None)
        if rawlink is not None:
            rawlink(_cleanup) 
Example 27
Project: godot-zeronet-plugin   Author: zam-org   File: threading.py    GNU General Public License v2.0 5 votes vote down vote up
def _cleanup(g):
    __threading__._active.pop(id(g), None) 
Example 28
Project: godot-zeronet-plugin   Author: zam-org   File: threading.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        #_DummyThread_.__init__(self)

        # It'd be nice to use a pattern like "greenlet-%d", but maybe somebody out
        # there is checking thread names...
        self._name = self._Thread__name = __threading__._newname("DummyThread-%d")
        self._set_ident()

        __threading__._active[_get_ident()] = self
        g = getcurrent()
        rawlink = getattr(g, 'rawlink', None)
        if rawlink is not None:
            rawlink(_cleanup) 
Example 29
Project: godot-zeronet-plugin   Author: zam-org   File: threading.py    GNU General Public License v2.0 5 votes vote down vote up
def _cleanup(g):
    __threading__._active.pop(id(g), None) 
Example 30
Project: godot-zeronet-plugin   Author: zam-org   File: threading.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        #_DummyThread_.__init__(self)

        # It'd be nice to use a pattern like "greenlet-%d", but maybe somebody out
        # there is checking thread names...
        self._name = self._Thread__name = __threading__._newname("DummyThread-%d")
        self._set_ident()

        __threading__._active[_get_ident()] = self
        g = getcurrent()
        rawlink = getattr(g, 'rawlink', None)
        if rawlink is not None:
            rawlink(_cleanup) 
Example 31
Project: TFTHelper   Author: AliMZaini   File: threading.py    MIT License 5 votes vote down vote up
def _cleanup(g):
    __threading__._active.pop(_get_ident(g), None) 
Example 32
Project: TFTHelper   Author: AliMZaini   File: threading.py    MIT License 5 votes vote down vote up
def __init__(self): # pylint:disable=super-init-not-called
        #_DummyThread_.__init__(self)

        # It'd be nice to use a pattern like "greenlet-%d", but maybe somebody out
        # there is checking thread names...
        self._name = self._Thread__name = __threading__._newname("DummyThread-%d")
        # All dummy threads in the same native thread share the same ident
        # (that of the native thread)
        self._set_ident()

        g = getcurrent()
        gid = _get_ident(g)
        __threading__._active[gid] = self
        rawlink = getattr(g, 'rawlink', None)
        if rawlink is not None:
            # raw greenlet.greenlet greenlets don't
            # have rawlink...
            rawlink(_cleanup)
        else:
            # ... so for them we use weakrefs.
            # See https://github.com/gevent/gevent/issues/918
            global _weakref
            if _weakref is None:
                _weakref = __import__('weakref')
            ref = _weakref.ref(g, _make_cleanup_id(gid))
            self.__raw_ref = ref 
Example 33
Project: TFTHelper   Author: AliMZaini   File: threading.py    MIT License 5 votes vote down vote up
def main_native_thread():
        main_threads = [v for v in __threading__._active.values()
                        if isinstance(v, __threading__._MainThread)]
        assert len(main_threads) == 1, "Too many main threads"

        return main_threads[0] 
Example 34
Project: TFTHelper   Author: AliMZaini   File: threading.py    MIT License 5 votes vote down vote up
def _gevent_will_monkey_patch(native_module, items, warn): # pylint:disable=unused-argument
    # Make sure the MainThread can be found by our current greenlet ID,
    # otherwise we get a new DummyThread, which cannot be joined.
    # Fixes tests in test_threading_2 under PyPy.
    main_thread = main_native_thread()
    if __threading__.current_thread() != main_thread:
        warn("Monkey-patching outside the main native thread. Some APIs "
             "will not be available. Expect a KeyError to be printed at shutdown.")
        return

    if _get_ident() not in __threading__._active:
        main_id = main_thread.ident
        del __threading__._active[main_id]
        main_thread._ident = main_thread._Thread__ident = _get_ident()
        __threading__._active[_get_ident()] = main_thread 
Example 35
Project: yappi   Author: mottosso   File: yappi.py    MIT License 5 votes vote down vote up
def _ctx_name_callback():
    """
    We don't use threading.current_thread() becuase it will deadlock if
    called when profiling threading._active_limbo_lock.acquire().
    See: #Issue48.
    """
    try:
        current_thread = threading._active[get_ident()]
        return current_thread.__class__.__name__
    except KeyError: 
        # Threads may not be registered yet in first few profile callbacks.
        return None 
Example 36
Project: Wallet   Author: superbitcoin   File: threading.py    MIT License 5 votes vote down vote up
def _cleanup(g):
    __threading__._active.pop(id(g), None) 
Example 37
Project: Wallet   Author: superbitcoin   File: threading.py    MIT License 5 votes vote down vote up
def __init__(self):
        #_DummyThread_.__init__(self)

        # It'd be nice to use a pattern like "greenlet-%d", but maybe somebody out
        # there is checking thread names...
        self._name = self._Thread__name = __threading__._newname("DummyThread-%d")
        self._set_ident()

        __threading__._active[_get_ident()] = self
        g = getcurrent()
        rawlink = getattr(g, 'rawlink', None)
        if rawlink is not None:
            rawlink(_cleanup) 
Example 38
Project: anybox.recipe.openerp   Author: anybox   File: openerp-server.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def dumpstacks(signum, frame):
    # code from http://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application#answer-2569696
    # modified for python 2.5 compatibility
    thread_map = dict(threading._active, **threading._limbo)
    id2name = dict([(threadId, thread.getName()) for threadId, thread in thread_map.items()])
    code = []
    for threadId, stack in sys._current_frames().items():
        code.append("\n# Thread: %s(%d)" % (id2name[threadId], threadId))
        for filename, lineno, name, line in traceback.extract_stack(stack):
            code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
            if line:
                code.append("  %s" % (line.strip()))
    logging.getLogger('dumpstacks').info("\n".join(code)) 
Example 39
Project: RealtimePythonChat   Author: quangtqag   File: threading.py    MIT License 5 votes vote down vote up
def _cleanup(g):
    __threading__._active.pop(id(g), None) 
Example 40
Project: RealtimePythonChat   Author: quangtqag   File: threading.py    MIT License 5 votes vote down vote up
def _make_cleanup_id(gid):
    def _(_r):
        __threading__._active.pop(gid, None)
    return _ 
Example 41
Project: Hot   Author: dsolimando   File: test_support.py    GNU General Public License v3.0 5 votes vote down vote up
def threading_setup():
    import threading
    return len(threading._active), 0 
Example 42
Project: Hot   Author: dsolimando   File: test_support.py    GNU General Public License v3.0 5 votes vote down vote up
def threading_cleanup(num_active, num_limbo):
    import threading
    import time

    _MAX_COUNT = 10
    count = 0
    while len(threading._active) != num_active and count < _MAX_COUNT:
        count += 1
        time.sleep(0.1) 
Example 43
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_threading.py    GNU General Public License v3.0 5 votes vote down vote up
def test_ident_of_no_threading_threads(self):
        # The ident still must work for the main thread and dummy threads.
        self.assertIsNotNone(threading.currentThread().ident)
        def f():
            ident.append(threading.currentThread().ident)
            done.set()
        done = threading.Event()
        ident = []
        _thread.start_new_thread(f, ())
        done.wait()
        self.assertIsNotNone(ident[0])
        # Kill the "immortal" _DummyThread
        del threading._active[ident[0]]

    # run with a small(ish) thread stack size (256kB) 
Example 44
Project: easypy   Author: weka-io   File: sync.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __repr__(self):
        owner, count = self._get_data()
        try:
            owner = threading._active[owner].name
        except KeyError:
            pass
        if owner:
            return "<{}, owned by <{}>x{} for {}>".format(self._name, owner, count, self._lease_timer.elapsed)
        else:
            return "<{}, unowned>".format(self._name) 
Example 45
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: attach_script.py    MIT License 4 votes vote down vote up
def fix_main_thread_id(on_warn=lambda msg:None, on_exception=lambda msg:None, on_critical=lambda msg:None):
    # This means that we weren't able to import threading in the main thread (which most
    # likely means that the main thread is paused or in some very long operation).
    # In this case we'll import threading here and hotfix what may be wrong in the threading
    # module (if we're on Windows where we create a thread to do the attach and on Linux
    # we are not certain on which thread we're executing this code).
    #
    # The code below is a workaround for https://bugs.python.org/issue37416
    import sys
    import threading

    try:
        with threading._active_limbo_lock:
            main_thread_instance = get_main_thread_instance(threading)

            if sys.platform == 'win32':
                # On windows this code would be called in a secondary thread, so,
                # the current thread is unlikely to be the main thread.
                if hasattr(threading, '_get_ident'):
                    unlikely_thread_id = threading._get_ident()  # py2
                else:
                    unlikely_thread_id = threading.get_ident()  # py3
            else:
                unlikely_thread_id = None

            main_thread_id, critical_warning = get_main_thread_id(unlikely_thread_id)

            if main_thread_id is not None:
                main_thread_id_attr = '_ident'
                if not hasattr(main_thread_instance, main_thread_id_attr):
                    main_thread_id_attr = '_Thread__ident'
                    assert hasattr(main_thread_instance, main_thread_id_attr)

                if main_thread_id != getattr(main_thread_instance, main_thread_id_attr):
                    # Note that we also have to reset the '_tstack_lock' for a regular lock.
                    # This is needed to avoid an error on shutdown because this lock is bound
                    # to the thread state and will be released when the secondary thread
                    # that initialized the lock is finished -- making an assert fail during
                    # process shutdown.
                    main_thread_instance._tstate_lock = threading._allocate_lock()
                    main_thread_instance._tstate_lock.acquire()

                    # Actually patch the thread ident as well as the threading._active dict
                    # (we should have the _active_limbo_lock to do that).
                    threading._active.pop(getattr(main_thread_instance, main_thread_id_attr), None)
                    setattr(main_thread_instance, main_thread_id_attr, main_thread_id)
                    threading._active[getattr(main_thread_instance, main_thread_id_attr)] = main_thread_instance

        # Note: only import from pydevd after the patching is done (we want to do the minimum
        # possible when doing that patching).
        on_warn('The threading module was not imported by user code in the main thread. The debugger will attempt to work around https://bugs.python.org/issue37416.')

        if critical_warning:
            on_critical('Issue found when debugger was trying to work around https://bugs.python.org/issue37416:\n%s' % (critical_warning,))
    except:
        on_exception('Error patching main thread id.') 
Example 46
Project: TFTHelper   Author: AliMZaini   File: test__threading_monkey_in_thread.py    MIT License 4 votes vote down vote up
def test_patch_in_thread(self):
        all_warnings = []
        try:
            get_ident = threading.get_ident
        except AttributeError:
            get_ident = threading._get_ident

        def process_warnings(warnings):
            all_warnings.extend(warnings)
        monkey._process_warnings = process_warnings

        current = threading.current_thread()
        current_id = get_ident()

        def target():
            tcurrent = threading.current_thread()
            monkey.patch_all()
            tcurrent2 = threading.current_thread()
            self.assertIsNot(tcurrent, current)
            # We get a dummy thread now
            self.assertIsNot(tcurrent, tcurrent2)

        thread = threading.Thread(target=target)
        thread.start()
        try:
            thread.join()
        except: # pylint:disable=bare-except
            # XXX: This can raise LoopExit in some cases.
            greentest.reraiseFlakyTestRaceCondition()

        self.assertNotIsInstance(current, threading._DummyThread)
        self.assertIsInstance(current, monkey.get_original('threading', 'Thread'))


        # We generated some warnings
        if sys.version_info >= (3, 4):
            self.assertEqual(all_warnings,
                             ['Monkey-patching outside the main native thread. Some APIs will not be '
                              'available. Expect a KeyError to be printed at shutdown.',
                              'Monkey-patching not on the main thread; threading.main_thread().join() '
                              'will hang from a greenlet'])
        else:
            self.assertEqual(all_warnings,
                             ['Monkey-patching outside the main native thread. Some APIs will not be '
                              'available. Expect a KeyError to be printed at shutdown.'])


        # Manual clean up so we don't get a KeyError
        del threading._active[current_id]
        threading._active[(getattr(threading, 'get_ident', None) or threading._get_ident)()] = current 
Example 47
Project: dotfiles   Author: xbaysal11   File: attach_script.py    GNU General Public License v3.0 4 votes vote down vote up
def fix_main_thread_id(on_warn=lambda msg:None, on_exception=lambda msg:None, on_critical=lambda msg:None):
    # This means that we weren't able to import threading in the main thread (which most
    # likely means that the main thread is paused or in some very long operation).
    # In this case we'll import threading here and hotfix what may be wrong in the threading
    # module (if we're on Windows where we create a thread to do the attach and on Linux
    # we are not certain on which thread we're executing this code).
    #
    # The code below is a workaround for https://bugs.python.org/issue37416
    import sys
    import threading

    try:
        with threading._active_limbo_lock:
            main_thread_instance = get_main_thread_instance(threading)

            if sys.platform == 'win32':
                # On windows this code would be called in a secondary thread, so,
                # the current thread is unlikely to be the main thread.
                if hasattr(threading, '_get_ident'):
                    unlikely_thread_id = threading._get_ident()  # py2
                else:
                    unlikely_thread_id = threading.get_ident()  # py3
            else:
                unlikely_thread_id = None

            main_thread_id, critical_warning = get_main_thread_id(unlikely_thread_id)

            if main_thread_id is not None:
                main_thread_id_attr = '_ident'
                if not hasattr(main_thread_instance, main_thread_id_attr):
                    main_thread_id_attr = '_Thread__ident'
                    assert hasattr(main_thread_instance, main_thread_id_attr)

                if main_thread_id != getattr(main_thread_instance, main_thread_id_attr):
                    # Note that we also have to reset the '_tstack_lock' for a regular lock.
                    # This is needed to avoid an error on shutdown because this lock is bound
                    # to the thread state and will be released when the secondary thread
                    # that initialized the lock is finished -- making an assert fail during
                    # process shutdown.
                    main_thread_instance._tstate_lock = threading._allocate_lock()
                    main_thread_instance._tstate_lock.acquire()

                    # Actually patch the thread ident as well as the threading._active dict
                    # (we should have the _active_limbo_lock to do that).
                    threading._active.pop(getattr(main_thread_instance, main_thread_id_attr), None)
                    setattr(main_thread_instance, main_thread_id_attr, main_thread_id)
                    threading._active[getattr(main_thread_instance, main_thread_id_attr)] = main_thread_instance

        # Note: only import from pydevd after the patching is done (we want to do the minimum
        # possible when doing that patching).
        on_warn('The threading module was not imported by user code in the main thread. The debugger will attempt to work around https://bugs.python.org/issue37416.')

        if critical_warning:
            on_critical('Issue found when debugger was trying to work around https://bugs.python.org/issue37416:\n%s' % (critical_warning,))
    except:
        on_exception('Error patching main thread id.')