Python threading.main_thread() Examples

The following are 30 code examples of threading.main_thread(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module threading , or try the search function .
Example #1
Source File: zmirror.py    From zmirror with MIT License 7 votes vote down vote up
def cron_task_host():
    """定时任务宿主, 每分钟检查一次列表, 运行时间到了的定时任务"""
    while True:
        # 当全局开关关闭时, 自动退出线程
        if not enable_cron_tasks:
            if threading.current_thread() != threading.main_thread():
                exit()
            else:
                return

        sleep(60)
        try:
            task_scheduler.run()
        except:  # coverage: exclude
            errprint('ErrorDuringExecutingCronTasks')
            traceback.print_exc() 
Example #2
Source File: test_threading.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_3_join_in_forked_from_thread(self):
        # Like the test above, but fork() was called from a worker thread
        # In the forked process, the main Thread object must be marked as stopped.

        script = """if 1:
            main_thread = threading.current_thread()
            def worker():
                childpid = os.fork()
                if childpid != 0:
                    os.waitpid(childpid, 0)
                    sys.exit(0)

                t = threading.Thread(target=joiningfunc,
                                     args=(main_thread,))
                print('end of main')
                t.start()
                t.join() # Should not block: main_thread is already stopped

            w = threading.Thread(target=worker)
            w.start()
            """
        self._run_and_join(script) 
Example #3
Source File: main_dlg.py    From dash-masternode-tool with MIT License 6 votes vote down vote up
def update_edit_controls_state(self):
        def update_fun():
            editing = (self.editing_enabled and self.cur_masternode is not None)
            self.action_gen_mn_priv_key_uncompressed.setEnabled(editing)
            self.action_gen_mn_priv_key_compressed.setEnabled(editing)
            self.btnDeleteMn.setEnabled(self.cur_masternode is not None)
            self.btnEditMn.setEnabled(not self.editing_enabled and self.cur_masternode is not None)
            self.btnCancelEditingMn.setEnabled(self.editing_enabled and self.cur_masternode is not None)
            self.btnDuplicateMn.setEnabled(self.cur_masternode is not None)
            self.action_save_config_file.setEnabled(self.app_config.is_modified())
            self.action_disconnect_hw.setEnabled(True if self.hw_client else False)
            self.btnRefreshMnStatus.setEnabled(self.cur_masternode is not None)
            self.btnRegisterDmn.setEnabled(self.cur_masternode is not None)
            self.action_sign_message_with_collateral_addr.setEnabled(self.cur_masternode is not None)
            self.action_sign_message_with_owner_key.setEnabled(self.cur_masternode is not None)
            self.action_sign_message_with_voting_key.setEnabled(self.cur_masternode is not None)
            self.update_mn_controls_state()
        if threading.current_thread() != threading.main_thread():
            self.call_in_main_thread(update_fun)
        else:
            update_fun() 
Example #4
Source File: wallet_dlg.py    From dash-masternode-tool with MIT License 6 votes vote down vote up
def show_loading_tx_animation(self):
        if not self.wdg_loading_txs_animation:
            def show():
                size = min(self.wdgSpinner.height(), self.wdgSpinner.width())
                g = self.wdgSpinner.geometry()
                g.setWidth(size)
                g.setHeight(size)
                self.wdgSpinner.setGeometry(g)
                self.wdg_loading_txs_animation = SpinnerWidget(self.wdgSpinner, size, '', 11)
                self.wdg_loading_txs_animation.show()

            if threading.current_thread() != threading.main_thread():
                if self.enable_synch_with_main_thread:
                    WndUtils.call_in_main_thread_ext(show, skip_if_main_thread_locked=True)
            else:
                show() 
Example #5
Source File: test_threading.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_main_thread_after_fork(self):
        code = """if 1:
            import os, threading

            pid = os.fork()
            if pid == 0:
                main = threading.main_thread()
                print(main.name)
                print(main.ident == threading.current_thread().ident)
                print(main.ident == threading.get_ident())
            else:
                os.waitpid(pid, 0)
        """
        _, out, err = assert_python_ok("-c", code)
        data = out.decode().replace('\r', '')
        self.assertEqual(err, b"")
        self.assertEqual(data, "MainThread\nTrue\nTrue\n") 
Example #6
Source File: test_threading.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_main_thread_after_fork_from_nonmain_thread(self):
        code = """if 1:
            import os, threading, sys

            def f():
                pid = os.fork()
                if pid == 0:
                    main = threading.main_thread()
                    print(main.name)
                    print(main.ident == threading.current_thread().ident)
                    print(main.ident == threading.get_ident())
                    # stdout is fully buffered because not a tty,
                    # we have to flush before exit.
                    sys.stdout.flush()
                else:
                    os.waitpid(pid, 0)

            th = threading.Thread(target=f)
            th.start()
            th.join()
        """
        _, out, err = assert_python_ok("-c", code)
        data = out.decode().replace('\r', '')
        self.assertEqual(err, b"")
        self.assertEqual(data, "Thread-1\nTrue\nTrue\n") 
Example #7
Source File: wallet_dlg.py    From dash-masternode-tool with MIT License 6 votes vote down vote up
def on_bip44_account_added(self, account: Bip44AccountType):
        """
        Called back from self.bip44_wallet after adding an item to the list of bip44 accounts. It is
        used in 'accounts view' mode for the subsequent display of read accounts.
        :param account: the account being added.
        """
        if not self.finishing:
            def fun():
                if self.utxo_src_mode == MAIN_VIEW_BIP44_ACCOUNTS:
                    self.account_list_model.add_account(account)

            log.debug('Adding account %s', account.id)
            if threading.current_thread() != threading.main_thread():
                if self.enable_synch_with_main_thread:
                    WndUtils.call_in_main_thread_ext(fun, skip_if_main_thread_locked=True)
            else:
                fun() 
Example #8
Source File: test_threading.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_3_join_in_forked_from_thread(self):
        # Like the test above, but fork() was called from a worker thread
        # In the forked process, the main Thread object must be marked as stopped.

        script = """if 1:
            main_thread = threading.current_thread()
            def worker():
                childpid = os.fork()
                if childpid != 0:
                    os.waitpid(childpid, 0)
                    sys.exit(0)

                t = threading.Thread(target=joiningfunc,
                                     args=(main_thread,))
                print('end of main')
                t.start()
                t.join() # Should not block: main_thread is already stopped

            w = threading.Thread(target=worker)
            w.start()
            """
        self._run_and_join(script) 
Example #9
Source File: plot.py    From layered with MIT License 6 votes vote down vote up
def start(self, work):
        """
        Hand the main thread to the window and continue work in the provided
        function. A state is passed as the first argument that contains a
        `running` flag. The function is expected to exit if the flag becomes
        false. The flag can also be set to false to stop the window event loop
        and continue in the main thread after the `start()` call.
        """
        assert threading.current_thread() == threading.main_thread()
        assert not self.state.running
        self.state.running = True
        self.thread = threading.Thread(target=work, args=(self.state,))
        self.thread.start()
        while self.state.running:
            try:
                before = time.time()
                self.update()
                duration = time.time() - before
                plt.pause(max(0.001, self.refresh - duration))
            except KeyboardInterrupt:
                self.state.running = False
                self.thread.join()
                return 
Example #10
Source File: wnd_utils.py    From dash-masternode-tool with MIT License 6 votes vote down vote up
def queryDlg(message, buttons=QMessageBox.Ok | QMessageBox.Cancel, default_button=QMessageBox.Ok,
            icon=QMessageBox.Information):

        def dlg(message, buttons, default_button, icon):
            msg = QMessageBox()
            msg.setIcon(icon)
            msg.setTextInteractionFlags(
                Qt.TextSelectableByMouse | Qt.TextSelectableByKeyboard | Qt.LinksAccessibleByMouse)

            # because of the bug: https://bugreports.qt.io/browse/QTBUG-48964
            # we'll convert a message to HTML format to avoid bolded font on Mac platform
            if message.find('<html') < 0:
                message = '<html style="font-weight:normal">' + message.replace('\n', '<br>') + '</html>'

            msg.setText(message)
            msg.setStandardButtons(buttons)
            msg.setDefaultButton(default_button)
            return msg.exec_()

        if threading.current_thread() != threading.main_thread():
            return WndUtils.call_in_main_thread(dlg, message, buttons, default_button, icon)
        else:
            return dlg(message, buttons, default_button, icon) 
Example #11
Source File: psw_cache.py    From dash-masternode-tool with MIT License 6 votes vote down vote up
def ask_for_password(username, host, message=None):
        if not SshPassCache.parent_window:
            raise Exception('SshPassCache not initialized')

        def query_psw(msg):
            password, ok = QInputDialog.getText(SshPassCache.parent_window, 'Password Dialog',
                                                msg, echo=QLineEdit.Password)
            return password, ok

        if not message:
            message = 'Enter password for ' + username + '@' + host + ':'

        if threading.current_thread() != threading.main_thread():
            password, ok = WndUtils.call_in_main_thread(query_psw, message)
        else:
            password, ok = query_psw(message)

        if not ok:
            raise CancelException
        return password 
Example #12
Source File: runner.py    From stackhut with Apache License 2.0 6 votes vote down vote up
def __init__(self, backend, hutcfg):
        log.debug('Starting Service Runner')
        self.backend = backend
        self.hutcfg = hutcfg
        # select the stack
        self.shim_cmd = shim_cmds.get(self.hutcfg.stack)
        if self.shim_cmd is None:
            raise RuntimeError("Unknown stack - {}".format(self.hutcfg.stack))

        # init the local runtime service
        self.runtime_server = RuntimeServer(backend)
        # init the rpc server
        self.rpc = rpc.StackHutRPC(self.backend, self.shim_cmd)

        assert threading.current_thread() == threading.main_thread()
        signal.signal(signal.SIGTERM, sigterm_handler)
        signal.signal(signal.SIGINT, sigterm_handler) 
Example #13
Source File: tools.py    From sisyphus with Mozilla Public License 2.0 6 votes vote down vote up
def default_handle_exception_interrupt_main_thread(func):
    """
    :param func: any function. usually run in another thread.
      If some exception occurs, it will interrupt the main thread (send KeyboardInterrupt to the main thread).
      If this is run in the main thread itself, it will raise SystemExit(1).
    :return: function func wrapped
    """
    import sys
    import _thread
    import threading

    def wrapped_func(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception:
            logging.error("Exception in thread %r:" % threading.current_thread())
            sys.excepthook(*sys.exc_info())
            if threading.current_thread() is not threading.main_thread():
                _thread.interrupt_main()
            raise SystemExit(1)

    return wrapped_func 
Example #14
Source File: test_threading.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_main_thread_after_fork_from_nonmain_thread(self):
        code = """if 1:
            import os, threading, sys

            def f():
                pid = os.fork()
                if pid == 0:
                    main = threading.main_thread()
                    print(main.name)
                    print(main.ident == threading.current_thread().ident)
                    print(main.ident == threading.get_ident())
                    # stdout is fully buffered because not a tty,
                    # we have to flush before exit.
                    sys.stdout.flush()
                else:
                    os.waitpid(pid, 0)

            th = threading.Thread(target=f)
            th.start()
            th.join()
        """
        _, out, err = assert_python_ok("-c", code)
        data = out.decode().replace('\r', '')
        self.assertEqual(err, b"")
        self.assertEqual(data, "Thread-1\nTrue\nTrue\n") 
Example #15
Source File: test_threading.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_main_thread_after_fork(self):
        code = """if 1:
            import os, threading

            pid = os.fork()
            if pid == 0:
                main = threading.main_thread()
                print(main.name)
                print(main.ident == threading.current_thread().ident)
                print(main.ident == threading.get_ident())
            else:
                os.waitpid(pid, 0)
        """
        _, out, err = assert_python_ok("-c", code)
        data = out.decode().replace('\r', '')
        self.assertEqual(err, b"")
        self.assertEqual(data, "MainThread\nTrue\nTrue\n") 
Example #16
Source File: test_threading.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_main_thread_after_fork(self):
        code = """if 1:
            import os, threading

            pid = os.fork()
            if pid == 0:
                main = threading.main_thread()
                print(main.name)
                print(main.ident == threading.current_thread().ident)
                print(main.ident == threading.get_ident())
            else:
                os.waitpid(pid, 0)
        """
        _, out, err = assert_python_ok("-c", code)
        data = out.decode().replace('\r', '')
        self.assertEqual(err, b"")
        self.assertEqual(data, "MainThread\nTrue\nTrue\n") 
Example #17
Source File: test_threading.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_main_thread_after_fork_from_nonmain_thread(self):
        code = """if 1:
            import os, threading, sys

            def f():
                pid = os.fork()
                if pid == 0:
                    main = threading.main_thread()
                    print(main.name)
                    print(main.ident == threading.current_thread().ident)
                    print(main.ident == threading.get_ident())
                    # stdout is fully buffered because not a tty,
                    # we have to flush before exit.
                    sys.stdout.flush()
                else:
                    os.waitpid(pid, 0)

            th = threading.Thread(target=f)
            th.start()
            th.join()
        """
        _, out, err = assert_python_ok("-c", code)
        data = out.decode().replace('\r', '')
        self.assertEqual(err, b"")
        self.assertEqual(data, "Thread-1\nTrue\nTrue\n") 
Example #18
Source File: test_threading.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_3_join_in_forked_from_thread(self):
        # Like the test above, but fork() was called from a worker thread
        # In the forked process, the main Thread object must be marked as stopped.

        script = """if 1:
            main_thread = threading.current_thread()
            def worker():
                childpid = os.fork()
                if childpid != 0:
                    os.waitpid(childpid, 0)
                    sys.exit(0)

                t = threading.Thread(target=joiningfunc,
                                     args=(main_thread,))
                print('end of main')
                t.start()
                t.join() # Should not block: main_thread is already stopped

            w = threading.Thread(target=worker)
            w.start()
            """
        self._run_and_join(script) 
Example #19
Source File: OWGeneSetEnrichment.py    From orange3-bioinformatics with GNU General Public License v3.0 6 votes vote down vote up
def _init_gene_sets_finished(self, f):
        assert self.thread() is QThread.currentThread()
        assert threading.current_thread() == threading.main_thread()
        assert self._task is not None
        assert self._task.future is f
        assert f.done()

        self._task = None
        self.progress_bar.finish()
        self.setStatusMessage('')

        try:
            results = f.result()  # type: list
            [self.data_model.appendRow(model_item) for model_item in results]
            self.filter_proxy_model.setSourceModel(self.data_model)
            self.data_view.selectionModel().selectionChanged.connect(self.commit)
            self._update_fdr()
            self.filter_data_view()
            self.set_selection()
            self.update_info_box()

        except Exception as ex:
            print(ex) 
Example #20
Source File: OWGeneSets.py    From orange3-bioinformatics with GNU General Public License v3.0 6 votes vote down vote up
def _init_gene_sets_finished(self, f):
        assert self.thread() is QThread.currentThread()
        assert threading.current_thread() == threading.main_thread()
        assert self._task is not None
        assert self._task.future is f
        assert f.done()

        self._task = None
        self.progress_bar.finish()
        self.setStatusMessage('')

        try:
            results = f.result()  # type: list
            [self.data_model.appendRow(model_item) for model_item in results]
            self.filter_proxy_model.setSourceModel(self.data_model)
            self.data_view.selectionModel().selectionChanged.connect(self.commit)
            self.filter_data_view()
            self.set_selection()
            self.update_info_box()
        except Exception as ex:
            print(ex)
        self.setBlocking(False) 
Example #21
Source File: TesterPresentContainer.py    From python-uds with MIT License 5 votes vote down vote up
def __testerPresentThread(target, **kwargs):

        def __tpWorker():
            #print("work thread started (should be once only)")
            while True:
                #print("inside worker loop")
                for tgt in TesterPresentContainer.testerPresentTargets:
                    try:
                        transmitting = tgt.isTransmitting()
                    except:
                        continue  # ... there's a problem with the stored target - e.g. target no longer in use, so a dead reference - so skip it
                    # ... otherwise we continue outside of the try/except block to avoid trapping any exceptions that may need to be propagated upwards
                    #print("target found")
                    if not transmitting:
                        #print("target not transmitting")
                        tpSessionRecord = tgt.testerPresentSessionRecord()
                        if tpSessionRecord['reqd']: # ... testPresent behaviour is required for the current diagnostic session
                            #print("tp required for target")
                            if tgt.sessionTimeSinceLastSend() >= tpSessionRecord['timeout']:
                                #print("timed out! - sending test present")
                                tgt.testerPresent()
                if not threading.main_thread().is_alive():
                    return
                time.sleep(1.0) # ... check if tester present is required every 1s (we are unlikely to require finer granularity).
                # Note: I'm avoiding direct wait mechanisms (of testerPresent TO) to allow for radical difference in behaviour for changing diagnostic sessions.
                # This can of course be changed.

        TesterPresentContainer.testerPresentTargets.add(target) # ... track a list of all possible concurrent targets, as we process tester present for all targets via one thread
        if TesterPresentContainer.testerPresentThreadRef is None:
            TesterPresentContainer.testerPresentThreadRef = threading.Thread(name='tpWorker', target=__tpWorker)
            TesterPresentContainer.testerPresentThreadRef.start() 
Example #22
Source File: player.py    From FeelUOwn with GNU General Public License v3.0 5 votes vote down vote up
def call_soon(func, loop):
    if threading.current_thread() is threading.main_thread():
        func()
    else:
        loop.call_soon_threadsafe(func) 
Example #23
Source File: executor.py    From gtui with GNU General Public License v3.0 5 votes vote down vote up
def get_main_thread_log_records(self):
        return self.name2records.get(threading.main_thread().name, []) 
Example #24
Source File: httrader.py    From OdooQuant with GNU General Public License v3.0 5 votes vote down vote up
def remove_heart_log(*args, **kwargs):
    if six.PY2:
        if threading.current_thread().name == 'MainThread':
            debug_log(*args, **kwargs)
    else:
        if threading.current_thread() == threading.main_thread():
            debug_log(*args, **kwargs) 
Example #25
Source File: test_threading.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_main_thread(self):
        main = threading.main_thread()
        self.assertEqual(main.name, 'MainThread')
        self.assertEqual(main.ident, threading.current_thread().ident)
        self.assertEqual(main.ident, threading.get_ident())

        def f():
            self.assertNotEqual(threading.main_thread().ident,
                                threading.current_thread().ident)
        th = threading.Thread(target=f)
        th.start()
        th.join() 
Example #26
Source File: debug_utils.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def listen():
    import threading

    if settings.DEBUG_STACK_DUMP_ENABLED and threading.current_thread() is threading.main_thread():
        signal.signal(settings.DEBUG_STACK_DUMP_SIGNAL, print_stack_traces) 
Example #27
Source File: FlameProfiler.py    From Uranium with GNU Lesser General Public License v3.0 5 votes vote down vote up
def isRecordingProfile() -> bool:
    """Return whether we are recording profiling information.

    :return: :type{bool} True if we are recording.
    """

    global record_profile
    return record_profile and threading.main_thread() is threading.current_thread() 
Example #28
Source File: test_threading.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_main_thread(self):
        main = threading.main_thread()
        self.assertEqual(main.name, 'MainThread')
        self.assertEqual(main.ident, threading.current_thread().ident)
        self.assertEqual(main.ident, threading.get_ident())

        def f():
            self.assertNotEqual(threading.main_thread().ident,
                                threading.current_thread().ident)
        th = threading.Thread(target=f)
        th.start()
        th.join() 
Example #29
Source File: multithread_test_case.py    From CrypTen with MIT License 5 votes vote down vote up
def setUp(self):
        super().setUp()

        if threading.current_thread() != threading.main_thread():
            return
        test_name = self._current_test_name()
        test_fn = getattr(self, test_name)
        self.exception_queue = queue.Queue()
        self.threads = [
            Thread(target=self._run, args=(test_fn, rank, self.world_size))
            for rank in range(self.world_size)
        ]
        for t in self.threads:
            t.start() 
Example #30
Source File: multithread_test_case.py    From CrypTen with MIT License 5 votes vote down vote up
def join_or_run(fn):
        @wraps(fn)
        def wrapper(self):
            if threading.current_thread() == threading.main_thread():
                self._join_threads()
            else:
                fn(self)

        return wrapper