Python threading._MainThread() Examples

The following are 30 code examples for showing how to use threading._MainThread(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module threading , or try the search function .

Example 1
Project: EMANet   Author: XiaLiPKU   File: dataloader.py    License: 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 2
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: Cura   Author: Ultimaker   File: Threading.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def call_on_qt_thread(func):
    @functools.wraps(func)
    def _call_on_qt_thread_wrapper(*args, **kwargs):
        # If the current thread is the main thread, which is the Qt thread, directly call the function.
        current_thread = threading.current_thread()
        if isinstance(current_thread, threading._MainThread):
            return func(*args, **kwargs)

        def _handle_call(ico, *args, **kwargs):
            ico.result = func(*args, **kwargs)
            ico.finish_event.set()
        inter_call_object = InterCallObject()
        new_args = tuple([inter_call_object] + list(args)[:])
        CuraApplication.getInstance().callLater(_handle_call, *new_args, **kwargs)
        inter_call_object.finish_event.wait()
        return inter_call_object.result
    return _call_on_qt_thread_wrapper 
Example 4
Project: PVN3D   Author: ethnhe   File: persistent_dataloader.py    License: 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.
        #  C._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: sanet_relocal_demo   Author: sfu-gruvi-3dv   File: persistent_dataloader.py    License: 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.
        #  C._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 6
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 7
Project: mt-dnn   Author: namisan   File: dataloader.py    License: 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 8
Project: dataflow   Author: tensorpack   File: concurrency.py    License: 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 9
Project: pyspider   Author: binux   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def __enter__(self):
            if not isinstance(threading.current_thread(), threading._MainThread):
                logging.warning("timeout only works on main thread, are you running pyspider in threads?")
                self.seconds = 0
            if self.seconds:
                signal.signal(signal.SIGALRM, self.handle_timeout)
                signal.alarm(int(math.ceil(self.seconds))) 
Example 10
Project: tox   Author: tox-dev   File: stdlib.py    License: 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 11
Project: moler   Author: nokia   File: connection_observer.py    License: 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 12
Project: pysat   Author: pysathq   File: _utils.py    License: MIT License 5 votes vote down vote up
def check():
        """
            The actual checker.
        """

        try:  # for Python > 3.4
            res = threading.current_thread() is threading.main_thread()
        except AttributeError:
            res = isinstance(threading.current_thread(), threading._MainThread)

        return res 
Example 13
Project: mlens   Author: flennerhag   File: _parallel_backends.py    License: 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 14
Project: PyDev.Debugger   Author: fabioz   File: test_utilities.py    License: Eclipse Public License 1.0 5 votes vote down vote up
def test_is_main_thread():
    from _pydevd_bundle.pydevd_utils import is_current_thread_main_thread
    from _pydevd_bundle.pydevd_utils import dump_threads
    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__,)

        try:
            from StringIO import StringIO
        except:
            from io import StringIO

        stream = StringIO()
        dump_threads(stream=stream)
        error_msg += '\n\n' + stream.getvalue()
        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 15
Project: n6   Author: CERT-Polska   File: timeout_callback_manager.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _in_main_thread():
        # noinspection PyUnresolvedReferences
        return isinstance(threading.current_thread(), threading._MainThread)


    #
    # Class preparation with external monkey patching 
Example 16
Project: etheno   Author: crytic   File: threadwrapper.py    License: 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 17
Project: RAFCON   Author: DLR-RM   File: start.py    License: Eclipse Public License 1.0 5 votes vote down vote up
def start_gtk():
    # check if twisted is imported
    if reactor_required():
        from twisted.internet import reactor
        import threading
        is_main_thread = isinstance(threading.current_thread(), threading._MainThread)
        reactor.run(installSignalHandlers=is_main_thread)
    else:
        Gtk.main() 
Example 18
Project: Fluid-Designer   Author: Microvellum   File: unix_events.py    License: 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 19
Project: Fluid-Designer   Author: Microvellum   File: unix_events.py    License: 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 20
Project: Fluid-Designer   Author: Microvellum   File: events.py    License: 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 21
Project: Imogen   Author: CedricGuillemet   File: unix_events.py    License: 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 22
Project: Imogen   Author: CedricGuillemet   File: unix_events.py    License: 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 23
Project: Imogen   Author: CedricGuillemet   File: events.py    License: 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 24
Project: pychess   Author: pychess   File: glib_events.py    License: 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 25
Project: lighthouse   Author: gaasedelen   File: misc.py    License: 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 26
Project: ironpython3   Author: IronLanguages   File: unix_events.py    License: 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 27
Project: ironpython3   Author: IronLanguages   File: unix_events.py    License: 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 28
Project: ironpython3   Author: IronLanguages   File: events.py    License: 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 29
Project: petridishnn   Author: microsoft   File: concurrency.py    License: MIT License 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 30
Project: ADL   Author: junsukchoe   File: concurrency.py    License: MIT License 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()