Python threading._MainThread() Examples

The following are code examples for showing how to use threading._MainThread(). 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: vscode-mayapy   Author: FXTD-ODYSSEY   File: test_utilities.py    MIT License 6 votes vote down vote up
def test_is_main_thread():
    from _pydevd_bundle.pydevd_utils import is_current_thread_main_thread
    if not is_current_thread_main_thread():
        error_msg = 'Current thread does not seem to be a main thread. Details:\n'
        current_thread = threading.current_thread()
        error_msg += 'Current thread: %s\n' % (current_thread,)

        if hasattr(threading, 'main_thread'):
            error_msg += 'Main thread found: %s\n' % (threading.main_thread(),)
        else:
            error_msg += 'Current main thread not instance of: %s (%s)' % (
                threading._MainThread, current_thread.__class__.__mro__,)

        raise AssertionError(error_msg)

    class NonMainThread(threading.Thread):

        def run(self):
            self.is_main_thread = is_current_thread_main_thread()

    non_main_thread = NonMainThread()
    non_main_thread.start()
    non_main_thread.join()
    assert not non_main_thread.is_main_thread 
Example 2
Project: EMANet   Author: XiaLiPKU   File: dataloader.py    GNU General Public License v3.0 6 votes vote down vote up
def _set_SIGCHLD_handler():
    # Windows doesn't support SIGCHLD handler
    if sys.platform == 'win32':
        return
    # can't set signal in child threads
    if not isinstance(threading.current_thread(), threading._MainThread):
        return
    global _SIGCHLD_handler_set
    if _SIGCHLD_handler_set:
        return
    previous_handler = signal.getsignal(signal.SIGCHLD)
    if not callable(previous_handler):
        previous_handler = None

    def handler(signum, frame):
        # This following call uses `waitid` with WNOHANG from C side. Therefore,
        # Python can still get and update the process status successfully.
        _error_if_any_worker_fails()
        if previous_handler is not None:
            previous_handler(signum, frame)

    signal.signal(signal.SIGCHLD, handler)
    _SIGCHLD_handler_set = True 
Example 3
Project: ObjectNet   Author: Nikronic   File: dataloader.py    MIT License 6 votes vote down vote up
def _set_SIGCHLD_handler():
    # Windows doesn't support SIGCHLD handler
    if sys.platform == 'win32':
        return
    # can't set signal in child threads
    if not isinstance(threading.current_thread(), threading._MainThread):
        return
    global _SIGCHLD_handler_set
    if _SIGCHLD_handler_set:
        return
    previous_handler = signal.getsignal(signal.SIGCHLD)
    if not callable(previous_handler):
        previous_handler = None

    def handler(signum, frame):
        # This following call uses `waitid` with WNOHANG from C side. Therefore,
        # Python can still get and update the process status successfully.
        _error_if_any_worker_fails()
        if previous_handler is not None:
            previous_handler(signum, frame)

    signal.signal(signal.SIGCHLD, handler)
    _SIGCHLD_handler_set = True 
Example 4
Project: semantic-segmentation-pytorch   Author: CSAILVision   File: dataloader.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _set_SIGCHLD_handler():
    # Windows doesn't support SIGCHLD handler
    if sys.platform == 'win32':
        return
    # can't set signal in child threads
    if not isinstance(threading.current_thread(), threading._MainThread):
        return
    global _SIGCHLD_handler_set
    if _SIGCHLD_handler_set:
        return
    previous_handler = signal.getsignal(signal.SIGCHLD)
    if not callable(previous_handler):
        previous_handler = None

    def handler(signum, frame):
        # This following call uses `waitid` with WNOHANG from C side. Therefore,
        # Python can still get and update the process status successfully.
        _error_if_any_worker_fails()
        if previous_handler is not None:
            previous_handler(signum, frame)

    signal.signal(signal.SIGCHLD, handler)
    _SIGCHLD_handler_set = True 
Example 5
Project: eden   Author: facebookexperimental   File: vfs.py    GNU General Public License v2.0 6 votes vote down vote up
def backgroundclosing(self, ui, expectedcount=-1):
        """Allow files to be closed asynchronously.

        When this context manager is active, ``backgroundclose`` can be passed
        to ``__call__``/``open`` to result in the file possibly being closed
        asynchronously, on a background thread.
        """
        # Sharing backgroundfilecloser between threads is complex and using
        # multiple instances puts us at risk of running out of file descriptors
        # only allow to use backgroundfilecloser when in main thread.
        if not isinstance(threading.currentThread(), threading._MainThread):
            yield
            return
        vfs = getattr(self, "vfs", self)
        if getattr(vfs, "_backgroundfilecloser", None):
            raise error.Abort(_("can only have 1 active background file closer"))

        with backgroundfilecloser(ui, expectedcount=expectedcount) as bfc:
            try:
                vfs._backgroundfilecloser = bfc
                yield bfc
            finally:
                vfs._backgroundfilecloser = None 
Example 6
Project: EMFT_ARCHIVE   Author: theendsofinvention   File: main_ui_interface.py    GNU General Public License v3.0 6 votes vote down vote up
def __call__(self, *args, **kwargs):
        if constant.MAIN_UI is None:
            raise RuntimeError('Main UI not initialized')

        # Check if this was called in the main thread (the one running Qt EventLoop)
        # noinspection PyProtectedMember
        if isinstance(threading.current_thread(), threading._MainThread):

            # If we are in the EventLoop, there's no need to dispatch the call to the a signal
            # noinspection PyProtectedMember
            constant.MAIN_UI._do('main_ui', self.func.__name__, args, kwargs)
        else:

            # Otherwise, queue the call
            constant.MAIN_UI.do('main_ui', self.func.__name__, *args, **kwargs)


# noinspection PyAbstractClass 
Example 7
Project: dotfiles_i3wm   Author: RomaniukVadim   File: golangconfig.py    GNU General Public License v3.0 6 votes vote down vote up
def debug_enabled():
    """
    Checks to see if the "debug" setting is true

    :raises:
        RuntimeError
            When the function is called from any thread but the UI thread

    :return:
        A boolean - if debug is enabled
    """

    # The Sublime Text API is not threadsafe in ST2, so we
    # double check here to prevent crashes
    if not isinstance(threading.current_thread(), threading._MainThread):
        raise RuntimeError('golangconfig.setting_value() must be called from the main thread')

    value = sublime.load_settings('golang.sublime-settings').get('debug')
    return False if value == '0' else bool(value) 
Example 8
Project: TorchRecord   Author: GeoffreyChen777   File: dataloader.py    MIT License 6 votes vote down vote up
def _set_SIGCHLD_handler():
    # Windows doesn't support SIGCHLD handler
    if sys.platform == 'win32':
        return
    # can't set signal in child threads
    if not isinstance(threading.current_thread(), threading._MainThread):
        return
    global _SIGCHLD_handler_set
    if _SIGCHLD_handler_set:
        return
    previous_handler = signal.getsignal(signal.SIGCHLD)
    if not callable(previous_handler):
        previous_handler = None

    def handler(signum, frame):
        # This following call uses `waitid` with WNOHANG from C side. Therefore,
        # Python can still get and update the process status successfully.
        _error_if_any_worker_fails()
        if previous_handler is not None:
            previous_handler(signum, frame)

    signal.signal(signal.SIGCHLD, handler)
    _SIGCHLD_handler_set = True 
Example 9
Project: semantic-segmentation-pytorch   Author: dailai   File: dataloader.py    MIT License 6 votes vote down vote up
def _set_SIGCHLD_handler():
    # Windows doesn't support SIGCHLD handler
    if sys.platform == 'win32':
        return
    # can't set signal in child threads
    if not isinstance(threading.current_thread(), threading._MainThread):
        return
    global _SIGCHLD_handler_set
    if _SIGCHLD_handler_set:
        return
    previous_handler = signal.getsignal(signal.SIGCHLD)
    if not callable(previous_handler):
        previous_handler = None

    def handler(signum, frame):
        # This following call uses `waitid` with WNOHANG from C side. Therefore,
        # Python can still get and update the process status successfully.
        _error_if_any_worker_fails()
        if previous_handler is not None:
            previous_handler(signum, frame)

    signal.signal(signal.SIGCHLD, handler)
    _SIGCHLD_handler_set = True 
Example 10
Project: dataflow   Author: tensorpack   File: concurrency.py    Apache License 2.0 5 votes vote down vote up
def is_main_thread():
    if six.PY2:
        return isinstance(threading.current_thread(), threading._MainThread)
    else:
        # a nicer solution with py3
        return threading.current_thread() == threading.main_thread() 
Example 11
Project: NiujiaoDebugger   Author: MrSrc   File: unix_events.py    GNU General Public License v3.0 5 votes vote down vote up
def _init_watcher(self):
        with events._lock:
            if self._watcher is None:  # pragma: no branch
                self._watcher = SafeChildWatcher()
                if isinstance(threading.current_thread(),
                              threading._MainThread):
                    self._watcher.attach_loop(self._local._loop) 
Example 12
Project: NiujiaoDebugger   Author: MrSrc   File: unix_events.py    GNU General Public License v3.0 5 votes vote down vote up
def set_event_loop(self, loop):
        """Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        """

        super().set_event_loop(loop)

        if (self._watcher is not None and
                isinstance(threading.current_thread(), threading._MainThread)):
            self._watcher.attach_loop(loop) 
Example 13
Project: NiujiaoDebugger   Author: MrSrc   File: events.py    GNU General Public License v3.0 5 votes vote down vote up
def get_event_loop(self):
        """Get the event loop.

        This may be None or an instance of EventLoop.
        """
        if (self._local._loop is None and
                not self._local._set_called and
                isinstance(threading.current_thread(), threading._MainThread)):
            self.set_event_loop(self.new_event_loop())

        if self._local._loop is None:
            raise RuntimeError('There is no current event loop in thread %r.'
                               % threading.current_thread().name)

        return self._local._loop 
Example 14
Project: tox   Author: tox-dev   File: stdlib.py    MIT License 5 votes vote down vote up
def is_main_thread():
    """returns true if we are within the main thread"""
    cur_thread = threading.current_thread()
    if sys.version_info >= (3, 4):
        return cur_thread is threading.main_thread()
    else:
        # noinspection PyUnresolvedReferences
        return isinstance(cur_thread, threading._MainThread)


# noinspection PyPep8Naming 
Example 15
Project: moler   Author: nokia   File: connection_observer.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def inside_main_thread():
        in_main_thread = isinstance(threading.current_thread(), threading._MainThread)
        return in_main_thread 
Example 16
Project: spotify-terminal   Author: marcdjulien   File: state.py    MIT License 5 votes vote down vote up
def switch_to_state(self, new_state):
        """Transition to a new State.

        Args:
            new_state (State): The new State to transition to.
        """
        if not isinstance(current_thread(), _MainThread):
            self.logger.info("Only the MainThread can switch states!")
            return

        logger.debug("State transition: %s -> %s", self.current_state, new_state)
        self.prev_state = self.current_state
        self.current_state = new_state 
Example 17
Project: code-inspector   Author: maxim5   File: bb1885f108ea651f4467ee4ac0ec11b1_unix_events.py    Apache License 2.0 5 votes vote down vote up
def _init_watcher(self):
        with events._lock:
            if self._watcher is None:  # pragma: no branch
                self._watcher = SafeChildWatcher()
                if isinstance(threading.current_thread(),
                              threading._MainThread):
                    self._watcher.attach_loop(self._local._loop) 
Example 18
Project: code-inspector   Author: maxim5   File: bb1885f108ea651f4467ee4ac0ec11b1_unix_events.py    Apache License 2.0 5 votes vote down vote up
def set_event_loop(self, loop):
        """Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        """

        super().set_event_loop(loop)

        if self._watcher is not None and \
            isinstance(threading.current_thread(), threading._MainThread):
            self._watcher.attach_loop(loop) 
Example 19
Project: tensorpack-mask-rcnn   Author: armandmcqueen   File: concurrency.py    Apache License 2.0 5 votes vote down vote up
def is_main_thread():
    if six.PY2:
        return isinstance(threading.current_thread(), threading._MainThread)
    else:
        # a nicer solution with py3
        return threading.current_thread() == threading.main_thread() 
Example 20
Project: Blockly-rduino-communication   Author: technologiescollege   File: unix_events.py    GNU General Public License v3.0 5 votes vote down vote up
def _init_watcher(self):
        with events._lock:
            if self._watcher is None:  # pragma: no branch
                self._watcher = SafeChildWatcher()
                if isinstance(threading.current_thread(),
                              threading._MainThread):
                    self._watcher.attach_loop(self._local._loop) 
Example 21
Project: Blockly-rduino-communication   Author: technologiescollege   File: unix_events.py    GNU General Public License v3.0 5 votes vote down vote up
def set_event_loop(self, loop):
        """Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        """

        super().set_event_loop(loop)

        if self._watcher is not None and \
            isinstance(threading.current_thread(), threading._MainThread):
            self._watcher.attach_loop(loop) 
Example 22
Project: Blockly-rduino-communication   Author: technologiescollege   File: events.py    GNU General Public License v3.0 5 votes vote down vote up
def get_event_loop(self):
        """Get the event loop.

        This may be None or an instance of EventLoop.
        """
        if (self._local._loop is None and
            not self._local._set_called and
            isinstance(threading.current_thread(), threading._MainThread)):
            self.set_event_loop(self.new_event_loop())
        if self._local._loop is None:
            raise RuntimeError('There is no current event loop in thread %r.'
                               % threading.current_thread().name)
        return self._local._loop 
Example 23
Project: mlens   Author: flennerhag   File: _parallel_backends.py    MIT License 5 votes vote down vote up
def effective_n_jobs(self, n_jobs):
        """Determine the number of jobs which are going to run in parallel.

        This also checks if we are attempting to create a nested parallel
        loop.
        """
        if mp is None:
            return 1

        if mp.current_process().daemon:
            # Daemonic processes cannot have children
            if n_jobs != 1:
                warnings.warn(
                    'Multiprocessing-backed parallel loops cannot be nested,'
                    ' setting n_jobs=1',
                    stacklevel=3)
            return 1

        if not isinstance(threading.current_thread(), threading._MainThread):
            # Prevent posix fork inside in non-main posix threads
            warnings.warn(
                'Multiprocessing-backed parallel loops cannot be nested'
                ' below threads, setting n_jobs=1',
                stacklevel=3)
            return 1

        return super(MultiprocessingBackend, self).effective_n_jobs(n_jobs) 
Example 24
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: unix_events.py    GNU General Public License v2.0 5 votes vote down vote up
def _init_watcher(self):
        with events._lock:
            if self._watcher is None:  # pragma: no branch
                self._watcher = SafeChildWatcher()
                if isinstance(threading.current_thread(),
                              threading._MainThread):
                    self._watcher.attach_loop(self._local._loop) 
Example 25
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: unix_events.py    GNU General Public License v2.0 5 votes vote down vote up
def set_event_loop(self, loop):
        """Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        """

        super().set_event_loop(loop)

        if (self._watcher is not None and
                isinstance(threading.current_thread(), threading._MainThread)):
            self._watcher.attach_loop(loop) 
Example 26
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: events.py    GNU General Public License v2.0 5 votes vote down vote up
def get_event_loop(self):
        """Get the event loop for the current context.

        Returns an instance of EventLoop or raises an exception.
        """
        if (self._local._loop is None and
                not self._local._set_called and
                isinstance(threading.current_thread(), threading._MainThread)):
            self.set_event_loop(self.new_event_loop())

        if self._local._loop is None:
            raise RuntimeError('There is no current event loop in thread %r.'
                               % threading.current_thread().name)

        return self._local._loop 
Example 27
Project: aws-lambda-runtime-pypy   Author: uscheller   File: unix_events.py    Apache License 2.0 5 votes vote down vote up
def _init_watcher(self):
        with events._lock:
            if self._watcher is None:  # pragma: no branch
                self._watcher = SafeChildWatcher()
                if isinstance(threading.current_thread(),
                              threading._MainThread):
                    self._watcher.attach_loop(self._local._loop) 
Example 28
Project: aws-lambda-runtime-pypy   Author: uscheller   File: unix_events.py    Apache License 2.0 5 votes vote down vote up
def set_event_loop(self, loop):
        """Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        """

        super().set_event_loop(loop)

        if self._watcher is not None and \
            isinstance(threading.current_thread(), threading._MainThread):
            self._watcher.attach_loop(loop) 
Example 29
Project: aws-lambda-runtime-pypy   Author: uscheller   File: events.py    Apache License 2.0 5 votes vote down vote up
def get_event_loop(self):
        """Get the event loop.

        This may be None or an instance of EventLoop.
        """
        if (self._local._loop is None and
            not self._local._set_called and
            isinstance(threading.current_thread(), threading._MainThread)):
            self.set_event_loop(self.new_event_loop())
        if self._local._loop is None:
            raise RuntimeError('There is no current event loop in thread %r.'
                               % threading.current_thread().name)
        return self._local._loop 
Example 30
Project: jobs   Author: josiahcarlson   File: jobs.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def handle_auto_shutdown():
    global ATEXIT_SET, SIGNAL_SET, OLD_SIGNAL
    if not ATEXIT_SET:
        ATEXIT_SET = atexit.register(_signal_handler)

    if not SIGNAL_SET and isinstance(threading.currentThread(), threading._MainThread):
        SIGNAL_SET, OLD_SIGNAL = True, signal.signal(signal.SIGTERM, _signal_handler) 
Example 31
Project: setup   Author: mindbender-studio   File: unix_events.py    MIT License 5 votes vote down vote up
def _init_watcher(self):
        with events._lock:
            if self._watcher is None:  # pragma: no branch
                self._watcher = SafeChildWatcher()
                if isinstance(threading.current_thread(),
                              threading._MainThread):
                    self._watcher.attach_loop(self._local._loop) 
Example 32
Project: setup   Author: mindbender-studio   File: unix_events.py    MIT License 5 votes vote down vote up
def set_event_loop(self, loop):
        """Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        """

        super().set_event_loop(loop)

        if self._watcher is not None and \
            isinstance(threading.current_thread(), threading._MainThread):
            self._watcher.attach_loop(loop) 
Example 33
Project: setup   Author: mindbender-studio   File: events.py    MIT License 5 votes vote down vote up
def get_event_loop(self):
        """Get the event loop.

        This may be None or an instance of EventLoop.
        """
        if (self._local._loop is None and
            not self._local._set_called and
            isinstance(threading.current_thread(), threading._MainThread)):
            self.set_event_loop(self.new_event_loop())
        if self._local._loop is None:
            raise RuntimeError('There is no current event loop in thread %r.'
                               % threading.current_thread().name)
        return self._local._loop 
Example 34
Project: RPGOne   Author: RTHMaK   File: _parallel_backends.py    Apache License 2.0 5 votes vote down vote up
def effective_n_jobs(self, n_jobs):
        """Determine the number of jobs which are going to run in parallel.

        This also checks if we are attempting to create a nested parallel
        loop.
        """
        if mp is None:
            return 1

        if mp.current_process().daemon:
            # Daemonic processes cannot have children
            if n_jobs != 1:
                warnings.warn(
                    'Multiprocessing-backed parallel loops cannot be nested,'
                    ' setting n_jobs=1',
                    stacklevel=3)
            return 1

        if not isinstance(threading.current_thread(), threading._MainThread):
            # Prevent posix fork inside in non-main posix threads
            warnings.warn(
                'Multiprocessing-backed parallel loops cannot be nested'
                ' below threads, setting n_jobs=1',
                stacklevel=3)
            return 1

        return super(MultiprocessingBackend, self).effective_n_jobs(n_jobs) 
Example 35
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 36
Project: etheno   Author: crytic   File: threadwrapper.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def is_main_thread():
    return isinstance(threading.current_thread(), threading._MainThread) 
Example 37
Project: sublime_debugger   Author: daveleroy   File: unix_events.py    MIT License 5 votes vote down vote up
def _init_watcher(self):
        with events._lock:
            if self._watcher is None:  # pragma: no branch
                self._watcher = SafeChildWatcher()
                if isinstance(threading.current_thread(),
                              threading._MainThread):
                    self._watcher.attach_loop(self._local._loop) 
Example 38
Project: sublime_debugger   Author: daveleroy   File: unix_events.py    MIT License 5 votes vote down vote up
def set_event_loop(self, loop):
        """Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        """

        super().set_event_loop(loop)

        if self._watcher is not None and \
            isinstance(threading.current_thread(), threading._MainThread):
            self._watcher.attach_loop(loop) 
Example 39
Project: sublime_debugger   Author: daveleroy   File: events.py    MIT License 5 votes vote down vote up
def get_event_loop(self):
        """Get the event loop.

        This may be None or an instance of EventLoop.
        """
        if (self._local._loop is None and
            not self._local._set_called and
            isinstance(threading.current_thread(), threading._MainThread)):
            self.set_event_loop(self.new_event_loop())
        if self._local._loop is None:
            raise RuntimeError('There is no current event loop in thread %r.'
                               % threading.current_thread().name)
        return self._local._loop 
Example 40
Project: sublime_debugger   Author: daveleroy   File: core.py    MIT License 5 votes vote down vote up
def is_main_thred() -> bool:
	return isinstance(threading.current_thread(), threading._MainThread) 
Example 41
Project: dotfiles_i3wm   Author: RomaniukVadim   File: tests.py    GNU General Public License v3.0 5 votes vote down vote up
def ensure_ui_thread():
    if not isinstance(threading.current_thread(), threading._MainThread):
        raise RuntimeError('Tests must be run in the UI thread') 
Example 42
Project: pychess   Author: pychess   File: glib_events.py    GNU General Public License v3.0 5 votes vote down vote up
def new_event_loop(self):
        """Create a new event loop and return it."""
        if not self._default_loop and isinstance(threading.current_thread(), threading._MainThread):
            l = self.get_default_loop()
        else:
            l = GLibEventLoop()
        l._policy = self

        return l 
Example 43
Project: lighthouse   Author: gaasedelen   File: misc.py    MIT License 5 votes vote down vote up
def is_mainthread():
    """
    Return a bool that indicates if this is the main application thread.
    """
    return isinstance(threading.current_thread(), threading._MainThread) 
Example 44
Project: Deribit_funding_rate_indicator   Author: Dimasik007   File: unix_events.py    MIT License 5 votes vote down vote up
def _init_watcher(self):
        with events._lock:
            if self._watcher is None:  # pragma: no branch
                self._watcher = SafeChildWatcher()
                if isinstance(threading.current_thread(),
                              threading._MainThread):
                    self._watcher.attach_loop(self._local._loop) 
Example 45
Project: Deribit_funding_rate_indicator   Author: Dimasik007   File: unix_events.py    MIT License 5 votes vote down vote up
def set_event_loop(self, loop):
        """Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        """

        super().set_event_loop(loop)

        if self._watcher is not None and \
            isinstance(threading.current_thread(), threading._MainThread):
            self._watcher.attach_loop(loop) 
Example 46
Project: Deribit_funding_rate_indicator   Author: Dimasik007   File: events.py    MIT License 5 votes vote down vote up
def get_event_loop(self):
        """Get the event loop.

        This may be None or an instance of EventLoop.
        """
        if (self._local._loop is None and
            not self._local._set_called and
            isinstance(threading.current_thread(), threading._MainThread)):
            self.set_event_loop(self.new_event_loop())
        if self._local._loop is None:
            raise RuntimeError('There is no current event loop in thread %r.'
                               % threading.current_thread().name)
        return self._local._loop 
Example 47
Project: wine-ml-on-aws-lambda   Author: pierreant   File: _parallel_backends.py    Apache License 2.0 5 votes vote down vote up
def effective_n_jobs(self, n_jobs):
        """Determine the number of jobs which are going to run in parallel.

        This also checks if we are attempting to create a nested parallel
        loop.
        """
        if mp is None:
            return 1

        if mp.current_process().daemon:
            # Daemonic processes cannot have children
            if n_jobs != 1:
                warnings.warn(
                    'Multiprocessing-backed parallel loops cannot be nested,'
                    ' setting n_jobs=1',
                    stacklevel=3)
            return 1

        if not isinstance(threading.current_thread(), threading._MainThread):
            # Prevent posix fork inside in non-main posix threads
            warnings.warn(
                'Multiprocessing-backed parallel loops cannot be nested'
                ' below threads, setting n_jobs=1',
                stacklevel=3)
            return 1

        return super(MultiprocessingBackend, self).effective_n_jobs(n_jobs) 
Example 48
Project: annotated-py-asyncio   Author: hhstore   File: unix_events.py    MIT License 5 votes vote down vote up
def _init_watcher(self):
        with events._lock:   # 锁
            if self._watcher is None:  # pragma: no branch
                self._watcher = SafeChildWatcher()       # 孩子监视器

                # 当前线程为主线程
                if isinstance(threading.current_thread(), threading._MainThread):
                    self._watcher.attach_loop(self._local._loop)

    #
    # 对外接口: 设置事件循环
    # 
Example 49
Project: annotated-py-asyncio   Author: hhstore   File: unix_events.py    MIT License 5 votes vote down vote up
def set_event_loop(self, loop):
        """Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        """
        super().set_event_loop(loop)

        # 当前线程为主线程
        if self._watcher is not None and \
            isinstance(threading.current_thread(), threading._MainThread):
            self._watcher.attach_loop(loop) 
Example 50
Project: annotated-py-asyncio   Author: hhstore   File: events.py    MIT License 5 votes vote down vote up
def get_event_loop(self):
        """Get the event loop.

        This may be None or an instance of EventLoop.
        """
        if (self._local._loop is None and
            not self._local._set_called and
            isinstance(threading.current_thread(), threading._MainThread)):
            self.set_event_loop(self.new_event_loop())
        if self._local._loop is None:
            raise RuntimeError('There is no current event loop in thread %r.'
                               % threading.current_thread().name)
        return self._local._loop 
Example 51
Project: debug-visualizer   Author: Kobzol   File: gui_util.py    GNU General Public License v3.0 5 votes vote down vote up
def assert_is_gui_thread():
    func = inspect.currentframe().f_back.f_back.f_code

    if not isinstance(threading.current_thread(), threading._MainThread):
        raise Exception("Not on the main thread at {0} ({1}:{2})".format(
            func.co_name, func.co_filename, func.co_firstlineno)) 
Example 52
Project: annotated-py-projects   Author: hhstore   File: unix_events.py    MIT License 5 votes vote down vote up
def _init_watcher(self):
        with events._lock:   # 锁
            if self._watcher is None:  # pragma: no branch
                self._watcher = SafeChildWatcher()       # 孩子监视器

                # 当前线程为主线程
                if isinstance(threading.current_thread(), threading._MainThread):
                    self._watcher.attach_loop(self._local._loop)

    #
    # 对外接口: 设置事件循环
    # 
Example 53
Project: annotated-py-projects   Author: hhstore   File: unix_events.py    MIT License 5 votes vote down vote up
def set_event_loop(self, loop):
        """Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        """
        super().set_event_loop(loop)

        # 当前线程为主线程
        if self._watcher is not None and \
            isinstance(threading.current_thread(), threading._MainThread):
            self._watcher.attach_loop(loop) 
Example 54
Project: annotated-py-projects   Author: hhstore   File: events.py    MIT License 5 votes vote down vote up
def get_event_loop(self):
        """Get the event loop.

        This may be None or an instance of EventLoop.
        """
        if (self._local._loop is None and
            not self._local._set_called and
            isinstance(threading.current_thread(), threading._MainThread)):
            self.set_event_loop(self.new_event_loop())
        if self._local._loop is None:
            raise RuntimeError('There is no current event loop in thread %r.'
                               % threading.current_thread().name)
        return self._local._loop 
Example 55
Project: docker   Author: getavalon   File: unix_events.py    MIT License 5 votes vote down vote up
def _init_watcher(self):
        with events._lock:
            if self._watcher is None:  # pragma: no branch
                self._watcher = SafeChildWatcher()
                if isinstance(threading.current_thread(),
                              threading._MainThread):
                    self._watcher.attach_loop(self._local._loop) 
Example 56
Project: docker   Author: getavalon   File: unix_events.py    MIT License 5 votes vote down vote up
def set_event_loop(self, loop):
        """Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        """

        super().set_event_loop(loop)

        if self._watcher is not None and \
            isinstance(threading.current_thread(), threading._MainThread):
            self._watcher.attach_loop(loop) 
Example 57
Project: docker   Author: getavalon   File: events.py    MIT License 5 votes vote down vote up
def get_event_loop(self):
        """Get the event loop.

        This may be None or an instance of EventLoop.
        """
        if (self._local._loop is None and
            not self._local._set_called and
            isinstance(threading.current_thread(), threading._MainThread)):
            self.set_event_loop(self.new_event_loop())
        if self._local._loop is None:
            raise RuntimeError('There is no current event loop in thread %r.'
                               % threading.current_thread().name)
        return self._local._loop 
Example 58
Project: Splunking-Crime   Author: nccgroup   File: _parallel_backends.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def effective_n_jobs(self, n_jobs):
        """Determine the number of jobs which are going to run in parallel.

        This also checks if we are attempting to create a nested parallel
        loop.
        """
        if mp is None:
            return 1

        if mp.current_process().daemon:
            # Daemonic processes cannot have children
            if n_jobs != 1:
                warnings.warn(
                    'Multiprocessing-backed parallel loops cannot be nested,'
                    ' setting n_jobs=1',
                    stacklevel=3)
            return 1

        if not isinstance(threading.current_thread(), threading._MainThread):
            # Prevent posix fork inside in non-main posix threads
            warnings.warn(
                'Multiprocessing-backed parallel loops cannot be nested'
                ' below threads, setting n_jobs=1',
                stacklevel=3)
            return 1

        return super(MultiprocessingBackend, self).effective_n_jobs(n_jobs) 
Example 59
Project: newterm   Author: codexns   File: tests.py    MIT License 5 votes vote down vote up
def ensure_ui_thread():
    if not isinstance(threading.current_thread(), threading._MainThread):
        raise RuntimeError('Tests must be run in the UI thread') 
Example 60
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: unix_events.py    GNU General Public License v3.0 5 votes vote down vote up
def _init_watcher(self):
        with events._lock:
            if self._watcher is None:  # pragma: no branch
                self._watcher = SafeChildWatcher()
                if isinstance(threading.current_thread(),
                              threading._MainThread):
                    self._watcher.attach_loop(self._local._loop) 
Example 61
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: unix_events.py    GNU General Public License v3.0 5 votes vote down vote up
def set_event_loop(self, loop):
        """Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        """

        super().set_event_loop(loop)

        if self._watcher is not None and \
            isinstance(threading.current_thread(), threading._MainThread):
            self._watcher.attach_loop(loop) 
Example 62
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: events.py    GNU General Public License v3.0 5 votes vote down vote up
def get_event_loop(self):
        """Get the event loop.

        This may be None or an instance of EventLoop.
        """
        if (self._local._loop is None and
            not self._local._set_called and
            isinstance(threading.current_thread(), threading._MainThread)):
            self.set_event_loop(self.new_event_loop())
        if self._local._loop is None:
            raise RuntimeError('There is no current event loop in thread %r.'
                               % threading.current_thread().name)
        return self._local._loop 
Example 63
Project: cells   Author: AlesTsurko   File: unix_events.py    MIT License 5 votes vote down vote up
def _init_watcher(self):
        with events._lock:
            if self._watcher is None:  # pragma: no branch
                self._watcher = SafeChildWatcher()
                if isinstance(threading.current_thread(),
                              threading._MainThread):
                    self._watcher.attach_loop(self._local._loop) 
Example 64
Project: cells   Author: AlesTsurko   File: unix_events.py    MIT License 5 votes vote down vote up
def set_event_loop(self, loop):
        """Set the event loop.

        As a side effect, if a child watcher was set before, then calling
        .set_event_loop() from the main thread will call .attach_loop(loop) on
        the child watcher.
        """

        super().set_event_loop(loop)

        if (self._watcher is not None and
                isinstance(threading.current_thread(), threading._MainThread)):
            self._watcher.attach_loop(loop) 
Example 65
Project: cells   Author: AlesTsurko   File: events.py    MIT License 5 votes vote down vote up
def get_event_loop(self):
        """Get the event loop for the current context.

        Returns an instance of EventLoop or raises an exception.
        """
        if (self._local._loop is None and
                not self._local._set_called and
                isinstance(threading.current_thread(), threading._MainThread)):
            self.set_event_loop(self.new_event_loop())

        if self._local._loop is None:
            raise RuntimeError('There is no current event loop in thread %r.'
                               % threading.current_thread().name)

        return self._local._loop 
Example 66
Project: atpbar   Author: alphatwirl   File: funcs.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def in_main_thread():
    try:
        return threading.current_thread() == threading.main_thread()
    except:
        # python 2
        return isinstance(threading.current_thread(), threading._MainThread)

##__________________________________________________________________|| 
Example 67
Project: artisan   Author: artisan-roaster-scope   File: main.py    GNU General Public License v3.0 5 votes vote down vote up
def sendmessage(self,message,append=True,style=None):
        if isinstance(threading.current_thread(), threading._MainThread):
            # we are running in the main thread thus we can call sendmessage_internal via a QTimer to avoid redraw issues
            QTimer.singleShot(2,lambda : self.sendmessage_internal(message,append,style))
        else:
            # we are not running in the main thread thus we CANNOT call sendmessage_internal via a QTimer
            aw.sendmessageSignal.emit(message,append,style) # we emit a signal to the main thread to resend this message and then process it via the QTimer
            #self.sendmessage_internal(message,append,style,repaint=False)
            # if this is executed via a QTimer we receive "QObject::startTimer: Timers can only be used with threads started with QThread" 
Example 68
Project: cdn-cache   Author: gbrunacci   File: wspbus.py    Apache License 2.0 4 votes vote down vote up
def block(self, interval=0.1):
        """Wait for the EXITING state, KeyboardInterrupt or SystemExit.

        This function is intended to be called only by the main thread.
        After waiting for the EXITING state, it also waits for all threads
        to terminate, and then calls os.execv if self.execv is True. This
        design allows another thread to call bus.restart, yet have the main
        thread perform the actual execv call (required on some platforms).
        """
        try:
            self.wait(states.EXITING, interval=interval, channel='main')
        except (KeyboardInterrupt, IOError):
            # The time.sleep call might raise
            # "IOError: [Errno 4] Interrupted function call" on KBInt.
            self.log('Keyboard Interrupt: shutting down bus')
            self.exit()
        except SystemExit:
            self.log('SystemExit raised: shutting down bus')
            self.exit()
            raise

        # Waiting for ALL child threads to finish is necessary on OS X.
        # See https://bitbucket.org/cherrypy/cherrypy/issue/581.
        # It's also good to let them all shut down before allowing
        # the main thread to call atexit handlers.
        # See https://bitbucket.org/cherrypy/cherrypy/issue/751.
        self.log("Waiting for child threads to terminate...")
        for t in threading.enumerate():
            # Validate the we're not trying to join the MainThread
            # that will cause a deadlock and the case exist when
            # implemented as a windows service and in any other case
            # that another thread executes cherrypy.engine.exit()
            if (
                    t != threading.currentThread() and
                    t.isAlive() and
                    not isinstance(t, threading._MainThread)
            ):
                # Note that any dummy (external) threads are always daemonic.
                if hasattr(threading.Thread, "daemon"):
                    # Python 2.6+
                    d = t.daemon
                else:
                    d = t.isDaemon()
                if not d:
                    self.log("Waiting for thread %s." % t.getName())
                    t.join()

        if self.execv:
            self._do_execv() 
Example 69
Project: Plex-CS   Author: zobe123   File: wspbus.py    GNU General Public License v3.0 4 votes vote down vote up
def block(self, interval=0.1):
        """Wait for the EXITING state, KeyboardInterrupt or SystemExit.

        This function is intended to be called only by the main thread.
        After waiting for the EXITING state, it also waits for all threads
        to terminate, and then calls os.execv if self.execv is True. This
        design allows another thread to call bus.restart, yet have the main
        thread perform the actual execv call (required on some platforms).
        """
        try:
            self.wait(states.EXITING, interval=interval, channel='main')
        except (KeyboardInterrupt, IOError):
            # The time.sleep call might raise
            # "IOError: [Errno 4] Interrupted function call" on KBInt.
            self.log('Keyboard Interrupt: shutting down bus')
            self.exit()
        except SystemExit:
            self.log('SystemExit raised: shutting down bus')
            self.exit()
            raise

        # Waiting for ALL child threads to finish is necessary on OS X.
        # See https://bitbucket.org/cherrypy/cherrypy/issue/581.
        # It's also good to let them all shut down before allowing
        # the main thread to call atexit handlers.
        # See https://bitbucket.org/cherrypy/cherrypy/issue/751.
        self.log("Waiting for child threads to terminate...")
        for t in threading.enumerate():
            # Validate the we're not trying to join the MainThread
            # that will cause a deadlock and the case exist when
            # implemented as a windows service and in any other case
            # that another thread executes cherrypy.engine.exit()
            if (
                    t != threading.currentThread() and
                    t.isAlive() and
                    not isinstance(t, threading._MainThread)
            ):
                # Note that any dummy (external) threads are always daemonic.
                if hasattr(threading.Thread, "daemon"):
                    # Python 2.6+
                    d = t.daemon
                else:
                    d = t.isDaemon()
                if not d:
                    self.log("Waiting for thread %s." % t.getName())
                    t.join()

        if self.execv:
            self._do_execv() 
Example 70
Project: opsbro   Author: naparuba   File: wspbus.py    MIT License 4 votes vote down vote up
def block(self, interval=0.1):
        """Wait for the EXITING state, KeyboardInterrupt or SystemExit.

        This function is intended to be called only by the main thread.
        After waiting for the EXITING state, it also waits for all threads
        to terminate, and then calls os.execv if self.execv is True. This
        design allows another thread to call bus.restart, yet have the main
        thread perform the actual execv call (required on some platforms).
        """
        try:
            self.wait(states.EXITING, interval=interval, channel='main')
        except (KeyboardInterrupt, IOError):
            # The time.sleep call might raise
            # "IOError: [Errno 4] Interrupted function call" on KBInt.
            self.log('Keyboard Interrupt: shutting down bus')
            self.exit()
        except SystemExit:
            self.log('SystemExit raised: shutting down bus')
            self.exit()
            raise

        # Waiting for ALL child threads to finish is necessary on OS X.
        # See https://bitbucket.org/cherrypy/cherrypy/issue/581.
        # It's also good to let them all shut down before allowing
        # the main thread to call atexit handlers.
        # See https://bitbucket.org/cherrypy/cherrypy/issue/751.
        self.log("Waiting for child threads to terminate...")
        for t in threading.enumerate():
            # Validate the we're not trying to join the MainThread
            # that will cause a deadlock and the case exist when
            # implemented as a windows service and in any other case
            # that another thread executes cherrypy.engine.exit()
            if (
                    t != threading.currentThread() and
                    t.isAlive() and
                    not isinstance(t, threading._MainThread)
            ):
                # Note that any dummy (external) threads are always daemonic.
                if hasattr(threading.Thread, "daemon"):
                    # Python 2.6+
                    d = t.daemon
                else:
                    d = t.isDaemon()
                if not d:
                    self.log("Waiting for thread %s." % t.getName())
                    t.join()

        if self.execv:
            self._do_execv() 
Example 71
Project: opsbro   Author: naparuba   File: threadmgr.py    MIT License 4 votes vote down vote up
def namer():
        # If no ctypes, like in a static python build: exit
        try:
            import ctypes
        except ImportError:
            return
        import threading
        import time
        from ctypes import wintypes
        
        class THREADNAME_INFO(ctypes.Structure):
            _pack_ = 8
            _fields_ = [
                ("dwType", wintypes.DWORD),
                ("szName", wintypes.LPCSTR),
                ("dwThreadID", wintypes.DWORD),
                ("dwFlags", wintypes.DWORD),
            ]
            
            
            def __init__(self):
                self.dwType = 0x1000
                self.dwFlags = 0
        
        def debugChecker():
            kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
            RaiseException = kernel32.RaiseException
            RaiseException.argtypes = [
                wintypes.DWORD, wintypes.DWORD, wintypes.DWORD,
                ctypes.c_void_p]
            RaiseException.restype = None
            
            IsDebuggerPresent = kernel32.IsDebuggerPresent
            IsDebuggerPresent.argtypes = []
            IsDebuggerPresent.restype = wintypes.BOOL
            MS_VC_EXCEPTION = 0x406D1388
            info = THREADNAME_INFO()
            while True:
                time.sleep(1)
                if IsDebuggerPresent():
                    for thread in threading.enumerate():
                        if thread.ident is None:
                            continue  # not started
                        if hasattr(threading, "_MainThread"):
                            if isinstance(thread, threading._MainThread):
                                continue  # don't name the main thread
                        info.szName = "%s (Python)" % (thread.name,)
                        info.dwThreadID = thread.ident
                        try:
                            RaiseException(MS_VC_EXCEPTION, 0,
                                           ctypes.sizeof(info) / ctypes.sizeof(
                                               ctypes.c_void_p),
                                           ctypes.addressof(info))
                        except:
                            pass
        
        
        dt = threading.Thread(target=debugChecker,
                              name="MSVC debugging support thread")
        dt.daemon = True
        dt.start() 
Example 72
Project: opsbro   Author: naparuba   File: threadmgr.py    MIT License 4 votes vote down vote up
def namer():
        # Return if python was build without ctypes (like in a static build)
        try:
            import ctypes
            import ctypes.util
        except ImportError:
            return
        import threading
        try:
            libpthread_path = ctypes.util.find_library("pthread")
        except RuntimeError:  # not found error on some system
            return
        # And some other returns None when not founded
        if not libpthread_path:
            return
        libpthread = ctypes.CDLL(libpthread_path)
        if not hasattr(libpthread, "pthread_setname_np"):
            return
        pthread_setname_np = libpthread.pthread_setname_np
        pthread_setname_np.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
        pthread_setname_np.restype = ctypes.c_int
        
        orig_setter = threading.Thread.__setattr__
        
        
        def attr_setter(self, name, value):
            orig_setter(self, name, value)
            if name == "name":
                ident = getattr(self, "ident", None)
                if ident:
                    try:
                        pthread_setname_np(ident, str(value[:15]))
                    except:
                        pass  # Don't care about failure to set name
        
        
        threading.Thread.__setattr__ = attr_setter
        
        # set the thread name to itself to trigger the new logic
        for thread in threading.enumerate():
            if thread.name:
                if hasattr(threading, "_MainThread"):
                    if isinstance(thread, threading._MainThread):
                        continue  # don't name the main thread
                thread.name = thread.name 
Example 73
Project: plugin.audio.squeezebox   Author: kodi-community-addons   File: wspbus.py    GNU General Public License v2.0 4 votes vote down vote up
def block(self, interval=0.1):
        """Wait for the EXITING state, KeyboardInterrupt or SystemExit.

        This function is intended to be called only by the main thread.
        After waiting for the EXITING state, it also waits for all threads
        to terminate, and then calls os.execv if self.execv is True. This
        design allows another thread to call bus.restart, yet have the main
        thread perform the actual execv call (required on some platforms).
        """
        try:
            self.wait(states.EXITING, interval=interval, channel='main')
        except (KeyboardInterrupt, IOError):
            # The time.sleep call might raise
            # "IOError: [Errno 4] Interrupted function call" on KBInt.
            self.log('Keyboard Interrupt: shutting down bus')
            self.exit()
        except SystemExit:
            self.log('SystemExit raised: shutting down bus')
            self.exit()
            raise

        # Waiting for ALL child threads to finish is necessary on OS X.
        # See https://github.com/cherrypy/cherrypy/issues/581.
        # It's also good to let them all shut down before allowing
        # the main thread to call atexit handlers.
        # See https://github.com/cherrypy/cherrypy/issues/751.
        self.log("Waiting for child threads to terminate...")
        for t in threading.enumerate():
            # Validate the we're not trying to join the MainThread
            # that will cause a deadlock and the case exist when
            # implemented as a windows service and in any other case
            # that another thread executes cherrypy.engine.exit()
            if (
                    t != threading.currentThread() and
                    t.isAlive() and
                    not isinstance(t, threading._MainThread)
            ):
                # Note that any dummy (external) threads are always daemonic.
                if hasattr(threading.Thread, "daemon"):
                    # Python 2.6+
                    d = t.daemon
                else:
                    d = t.isDaemon()
                if not d:
                    self.log("Waiting for thread %s." % t.getName())
                    t.join()

        if self.execv:
            self._do_execv() 
Example 74
Project: idapkg   Author: Jinmo   File: package.py    MIT License 4 votes vote down vote up
def load(self, force=False):
        """
        Actually does :code:`ida_loaders.load_plugin(paths)`, and updates IDAUSR variable.
        """
        if not force and self.path in os.environ.get('IDAUSR', ''):
            # Already loaded, just update sys.path for python imports
            sys.path.append(self.path)
            return

        env = str(_idausr_add(os.getenv('IDAUSR'), self.path))
        # XXX: find a more efficient way to ensure dependencies
        errors = []
        for dependency in self.metadata().get('dependencies', {}).keys():
            dep = LocalPackage.by_name(dependency)
            if not dep:
                errors.append('Dependency not found: %r' % dependency)
                continue
            dep.load()

        if errors:
            for error in errors:
                log.error(error)
            return

        def handler():
            assert isinstance(threading.current_thread(),
                              threading._MainThread)
            # Load plugins immediately
            # processors / loaders will be loaded on demand
            sys.path.append(self.path)

            # Update IDAUSR variable
            invalidate_idausr()
            putenv('IDAUSR', env)

            # Immediately load compatible plugins
            self._find_loadable_modules('plugins', ida_loader.load_plugin)

            # Find loadable processor modules, and if exists, invalidate cached process list (proccache).
            invalidates = []
            self._find_loadable_modules('procs', invalidates.append)

            if invalidates:
                invalidate_proccache()

        ida_kernwin.execute_sync(handler, ida_kernwin.MFF_FAST)