Python _thread.start_new_thread() Examples

The following are 30 code examples of _thread.start_new_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 _thread , or try the search function .
Example #1
Source File: module_utils.py    From QRLJacking with GNU General Public License v3.0 9 votes vote down vote up
def start_serving(self,host="0.0.0.0"):
        serve_dir = os.path.join(Settings.path,"core","www",self.name)
        f = open( os.path.join(serve_dir,"index.html"),"w")
        f.write(self.html)
        f.close()
        class ReusableTCPServer(socketserver.TCPServer):
            allow_reuse_address = True
            logging = False
        class MyHandler(http.server.SimpleHTTPRequestHandler):
            def __init__(self, *args, **kwargs):
                super().__init__(*args, directory=serve_dir, **kwargs)
            def log_message(self, format, *args):
                if self.server.logging:
                    http.server.SimpleHTTPRequestHandler.log_message(self, format, *args)

        self.httpd = ReusableTCPServer( (host, self.port), MyHandler)
        t = thread.start_new_thread(self.httpd.serve_forever, ()) 
Example #2
Source File: test_verify.py    From SwiftKitten with MIT License 7 votes vote down vote up
def _run_in_multiple_threads(test1):
    test1()
    import sys
    try:
        import thread
    except ImportError:
        import _thread as thread
    errors = []
    def wrapper(lock):
        try:
            test1()
        except:
            errors.append(sys.exc_info())
        lock.release()
    locks = []
    for i in range(10):
        _lock = thread.allocate_lock()
        _lock.acquire()
        thread.start_new_thread(wrapper, (_lock,))
        locks.append(_lock)
    for _lock in locks:
        _lock.acquire()
        if errors:
            raise errors[0][1] 
Example #3
Source File: backend_tests.py    From SwiftKitten with MIT License 7 votes vote down vote up
def test_init_once_multithread(self):
        import sys, time
        if sys.version_info < (3,):
            import thread
        else:
            import _thread as thread
        #
        def do_init():
            seen.append('init!')
            time.sleep(1)
            seen.append('init done')
            return 7
        ffi = FFI()
        seen = []
        for i in range(6):
            def f():
                res = ffi.init_once(do_init, "tag")
                seen.append(res)
            thread.start_new_thread(f, ())
        time.sleep(1.5)
        assert seen == ['init!', 'init done'] + 6 * [7] 
Example #4
Source File: main.py    From HanTTS with MIT License 7 votes vote down vote up
def speak(self, text):
        syllables = lazy_pinyin(text, style=pypinyin.TONE3)
        print(syllables)
        delay = 0
        
        def preprocess(syllables):
            temp = []
            for syllable in syllables:
                for p in TextToSpeech.punctuation:
                    syllable = syllable.replace(p, "")
                if syllable.isdigit():
                    syllable = atc.num2chinese(syllable)
                    new_sounds = lazy_pinyin(syllable, style=pypinyin.TONE3)
                    for e in new_sounds:
                        temp.append(e)
                else:
                    temp.append(syllable)
            return temp

        syllables = preprocess(syllables)
        for syllable in syllables:
            path = "syllables/"+syllable+".wav"
            _thread.start_new_thread(TextToSpeech._play_audio, (path, delay))
            delay += 0.355 
Example #5
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def intercept_threads(for_attach = False):
    thread.start_new_thread = thread_creator
    thread.start_new = thread_creator

    # If threading has already been imported (i.e. we're attaching), we must hot-patch threading._start_new_thread
    # so that new threads started using it will be intercepted by our code.
    #
    # On the other hand, if threading has not been imported, we must not import it ourselves, because it will then
    # treat the current thread as the main thread, which is incorrect when attaching because this code is executing
    # on an ephemeral debugger attach thread that will go away shortly. We don't need to hot-patch it in that case
    # anyway, because it will pick up the new thread.start_new_thread that we have set above when it's imported.
    global _threading
    if _threading is None and 'threading' in sys.modules:
        import threading
        _threading = threading
        _threading._start_new_thread = thread_creator

    global _INTERCEPTING_FOR_ATTACH
    _INTERCEPTING_FOR_ATTACH = for_attach 
Example #6
Source File: test_ffi_obj.py    From SwiftKitten with MIT License 6 votes vote down vote up
def test_init_once_multithread():
    if sys.version_info < (3,):
        import thread
    else:
        import _thread as thread
    import time
    #
    def do_init():
        print('init!')
        seen.append('init!')
        time.sleep(1)
        seen.append('init done')
        print('init done')
        return 7
    ffi = _cffi1_backend.FFI()
    seen = []
    for i in range(6):
        def f():
            res = ffi.init_once(do_init, "tag")
            seen.append(res)
        thread.start_new_thread(f, ())
    time.sleep(1.5)
    assert seen == ['init!', 'init done'] + 6 * [7] 
Example #7
Source File: test_verify1.py    From SwiftKitten with MIT License 6 votes vote down vote up
def _run_in_multiple_threads(test1):
    test1()
    import sys
    try:
        import thread
    except ImportError:
        import _thread as thread
    errors = []
    def wrapper(lock):
        try:
            test1()
        except:
            errors.append(sys.exc_info())
        lock.release()
    locks = []
    for i in range(10):
        _lock = thread.allocate_lock()
        _lock.acquire()
        thread.start_new_thread(wrapper, (_lock,))
        locks.append(_lock)
    for _lock in locks:
        _lock.acquire()
        if errors:
            raise errors[0][1] 
Example #8
Source File: ThreadableTest.py    From python-can-isotp with MIT License 6 votes vote down vote up
def _setUp(self):
        self.server_ready = threading.Event()
        self.client_ready = threading.Event()
        self.done = threading.Event()
        self.queue = queue.Queue(1)
        self.server_crashed = False

        # Do some munging to start the client test.
        methodname = self.id()
        i = methodname.rfind('.')
        methodname = methodname[i+1:]
        test_method = getattr(self, '_' + methodname)
        self.client_thread = thread.start_new_thread(self.clientRun, (test_method,))

        try:
            self.__setUp()
        except:
            self.server_crashed = True
            raise
        finally:
            self.server_ready.set()
        self.client_ready.wait() 
Example #9
Source File: test_ffi_obj.py    From SwiftKitten with MIT License 6 votes vote down vote up
def test_init_once_multithread_failure():
    if sys.version_info < (3,):
        import thread
    else:
        import _thread as thread
    import time
    def do_init():
        seen.append('init!')
        time.sleep(1)
        seen.append('oops')
        raise ValueError
    ffi = _cffi1_backend.FFI()
    seen = []
    for i in range(3):
        def f():
            py.test.raises(ValueError, ffi.init_once, do_init, "tag")
        thread.start_new_thread(f, ())
    i = 0
    while len(seen) < 6:
        i += 1
        assert i < 20
        time.sleep(0.51)
    assert seen == ['init!', 'oops'] * 3 
Example #10
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def intercept_threads(for_attach = False):
    thread.start_new_thread = thread_creator
    thread.start_new = thread_creator

    # If threading has already been imported (i.e. we're attaching), we must hot-patch threading._start_new_thread
    # so that new threads started using it will be intercepted by our code.
    #
    # On the other hand, if threading has not been imported, we must not import it ourselves, because it will then
    # treat the current thread as the main thread, which is incorrect when attaching because this code is executing
    # on an ephemeral debugger attach thread that will go away shortly. We don't need to hot-patch it in that case
    # anyway, because it will pick up the new thread.start_new_thread that we have set above when it's imported.
    global _threading
    if _threading is None and 'threading' in sys.modules:
        import threading
        _threading = threading
        _threading._start_new_thread = thread_creator

    global _INTERCEPTING_FOR_ATTACH
    _INTERCEPTING_FOR_ATTACH = for_attach 
Example #11
Source File: autoreload.py    From bioforum with MIT License 6 votes vote down vote up
def python_reloader(main_func, args, kwargs):
    if os.environ.get("RUN_MAIN") == "true":
        _thread.start_new_thread(main_func, args, kwargs)
        try:
            reloader_thread()
        except KeyboardInterrupt:
            pass
    else:
        try:
            exit_code = restart_with_reloader()
            if exit_code < 0:
                os.kill(os.getpid(), -exit_code)
            else:
                sys.exit(exit_code)
        except KeyboardInterrupt:
            pass 
Example #12
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def intercept_threads(for_attach = False):
    thread.start_new_thread = thread_creator
    thread.start_new = thread_creator

    # If threading has already been imported (i.e. we're attaching), we must hot-patch threading._start_new_thread
    # so that new threads started using it will be intercepted by our code.
    #
    # On the other hand, if threading has not been imported, we must not import it ourselves, because it will then
    # treat the current thread as the main thread, which is incorrect when attaching because this code is executing
    # on an ephemeral debugger attach thread that will go away shortly. We don't need to hot-patch it in that case
    # anyway, because it will pick up the new thread.start_new_thread that we have set above when it's imported.
    global _threading
    if _threading is None and 'threading' in sys.modules:
        import threading
        _threading = threading
        _threading._start_new_thread = thread_creator

    global _INTERCEPTING_FOR_ATTACH
    _INTERCEPTING_FOR_ATTACH = for_attach 
Example #13
Source File: visualstudio_py_debugger.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def intercept_threads(for_attach = False):
    thread.start_new_thread = thread_creator
    thread.start_new = thread_creator

    # If threading has already been imported (i.e. we're attaching), we must hot-patch threading._start_new_thread
    # so that new threads started using it will be intercepted by our code.
    #
    # On the other hand, if threading has not been imported, we must not import it ourselves, because it will then
    # treat the current thread as the main thread, which is incorrect when attaching because this code is executing
    # on an ephemeral debugger attach thread that will go away shortly. We don't need to hot-patch it in that case
    # anyway, because it will pick up the new thread.start_new_thread that we have set above when it's imported.
    global _threading
    if _threading is None and 'threading' in sys.modules:
        import threading
        _threading = threading
        _threading._start_new_thread = thread_creator

    global _INTERCEPTING_FOR_ATTACH
    _INTERCEPTING_FOR_ATTACH = for_attach 
Example #14
Source File: test_socket.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def _setUp(self):
        self.server_ready = threading.Event()
        self.client_ready = threading.Event()
        self.done = threading.Event()
        self.queue = queue.Queue(1)
        self.server_crashed = False

        # Do some munging to start the client test.
        methodname = self.id()
        i = methodname.rfind('.')
        methodname = methodname[i+1:]
        test_method = getattr(self, '_' + methodname)
        self.client_thread = thread.start_new_thread(
            self.clientRun, (test_method,))

        try:
            self.__setUp()
        except:
            self.server_crashed = True
            raise
        finally:
            self.server_ready.set()
        self.client_ready.wait() 
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_dummy_thread_after_fork(self):
        # Issue #14308: a dummy thread in the active list doesn't mess up
        # the after-fork mechanism.
        code = """if 1:
            import _thread, threading, os, time

            def background_thread(evt):
                # Creates and registers the _DummyThread instance
                threading.current_thread()
                evt.set()
                time.sleep(10)

            evt = threading.Event()
            _thread.start_new_thread(background_thread, (evt,))
            evt.wait()
            assert threading.active_count() == 2, threading.active_count()
            if os.fork() == 0:
                assert threading.active_count() == 1, threading.active_count()
                os._exit(0)
            else:
                os.wait()
        """
        _, out, err = assert_python_ok("-c", code)
        self.assertEqual(out, b'')
        self.assertEqual(err, b'') 
Example #16
Source File: visualstudio_py_repl.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def connect_using_socket(self, socket):
        self.conn = socket
        start_new_thread(self._repl_loop, ()) 
Example #17
Source File: visualstudio_py_repl.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, reason):
        self.reason = reason

# save the start_new_thread so we won't debug/break into the REPL comm thread. 
Example #18
Source File: visualstudio_py_repl.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def connect(self, port):
        self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.conn.connect(('127.0.0.1', port))

        # start a new thread for communicating w/ the remote process
        start_new_thread(self._repl_loop, ()) 
Example #19
Source File: visualstudio_py_repl.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fileno(self):
        if self.pipe is None:
            self.pipe = os.pipe()
            thread.start_new_thread(self.pipe_thread, (), {})

        return self.pipe[1] 
Example #20
Source File: visualstudio_py_repl.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fileno(self):
        if self.pipe is None:
            self.pipe = os.pipe()
            thread.start_new_thread(self.pipe_thread, (), {})

        return self.pipe[1] 
Example #21
Source File: telnetlib.py    From Imogen with MIT License 5 votes vote down vote up
def mt_interact(self):
        """Multithreaded version of interact()."""
        import _thread
        _thread.start_new_thread(self.listener, ())
        while 1:
            line = sys.stdin.readline()
            if not line:
                break
            self.write(line.encode('ascii')) 
Example #22
Source File: visualstudio_py_repl.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, reason):
        self.reason = reason

# save the start_new_thread so we won't debug/break into the REPL comm thread. 
Example #23
Source File: bottle3.py    From pyFileFixity with MIT License 5 votes vote down vote up
def reloader_run(server, app, interval):
    if os.environ.get('BOTTLE_CHILD') == 'true':
        # We are a child process
        files = dict()
        for module in list(sys.modules.values()):
            file_path = getattr(module, '__file__', None)
            if file_path and os.path.isfile(file_path):
                file_split = os.path.splitext(file_path)
                if file_split[1] in ('.py', '.pyc', '.pyo'):
                    file_path = file_split[0] + '.py'
                    files[file_path] = os.stat(file_path).st_mtime
        _thread.start_new_thread(server.run, (app,))
        while True:
            time.sleep(interval)
            for file_path, file_mtime in files.items():
                if not os.path.exists(file_path):
                    print("File changed: %s (deleted)" % file_path)
                elif os.stat(file_path).st_mtime > file_mtime:
                    print("File changed: %s (modified)" % file_path)
                else: continue
                print("Restarting...")
                app.serve = False
                time.sleep(interval) # be nice and wait for running requests
                sys.exit(3)
    while True:
        args = [sys.executable] + sys.argv
        environ = os.environ.copy()
        environ['BOTTLE_CHILD'] = 'true'
        exit_status = subprocess.call(args, env=environ)
        if exit_status != 3:
            sys.exit(exit_status)






# Templates 
Example #24
Source File: start.py    From tor-ip-changer with GNU General Public License v3.0 5 votes vote down vote up
def ipstart(self):
        self.start = timer()
        self.write('IP Changer started.\n', "green", 1)
        self.progressbar["style"] = "green.Horizontal.TProgressbar" 
        self.changermenu.entryconfig(0, state="disabled")
        self.changermenu.entryconfig(1, state="normal")
        
        _thread.start_new_thread(self.ipProc, ())  
        _thread.start_new_thread(self.appInfo, ())
            
    #funkce zastaveni zmeny IP 
Example #25
Source File: start.py    From tor-ip-changer with GNU General Public License v3.0 5 votes vote down vote up
def ipProc(self):
        _thread.start_new_thread(self.startnewIP, ())                                                                                                        
        _thread.start_new_thread(self.ip, ())
        
    #funkce startu zmeny IP 
Example #26
Source File: start.py    From tor-ip-changer with GNU General Public License v3.0 5 votes vote down vote up
def stoptor(self):
        self.tormenu.entryconfig(0, state="normal")
        self.tormenu.entryconfig(1, state="disabled")
        if self.meni == 1:
          _thread.start_new_thread(self.ipstop, ())
        
        SW_HIDE = 0
        os.system(r'killall tor')
        os.system(r'killall obfs4proxy')
        
        self.write("TOR server stopped. \n", "error", 1)   
        self.ident = random.random()
        if self.meni == 0:
            self.progressbar["value"] = 0
        self.bezi=0
        self.meni=0
        self.IPchanged = 0
        self.IPfetched = 0
        self.failed=0
        self.control = 15000
        self.proxy = 9050
        self.b = 0
        self.data = "Data/tordata%s" % self.b
        self.changermenu.entryconfig(0, state="disabled")
        self.changermenu.entryconfig(1, state="disabled")
        
    #funkce k pouziti bridges 
Example #27
Source File: start.py    From tor-ip-changer with GNU General Public License v3.0 5 votes vote down vote up
def starttor(self):      
        self.tormenu.entryconfig(0, state="disabled")
        self.tormenu.entryconfig(1, state="normal")
        self.progressbar["style"] = "blue.Horizontal.TProgressbar"
        self.progressbar["maximum"] = 100
        self.progressbar["value"] = 0
        _thread.start_new_thread(self.tor, ())
        
    #funkce zastaveni tora 
Example #28
Source File: start.py    From tor-ip-changer with GNU General Public License v3.0 5 votes vote down vote up
def startthings(self):
        time.sleep(1)
        if args.auto is not None:
            self.tormenu.entryconfig(0, state="disabled")
        _thread.start_new_thread(self.update, ())
        
    #funkce na prestart, overeni tora 
Example #29
Source File: start.py    From tor-ip-changer with GNU General Public License v3.0 5 votes vote down vote up
def showlog(self):
        self.logmenu.entryconfig(1, label = "Hide debug console", command=self.hidelog)
        _thread.start_new_thread(self.tail, ())
    
    #funkce na tail 
Example #30
Source File: start.py    From tor-ip-changer with GNU General Public License v3.0 5 votes vote down vote up
def help(self):
        _thread.start_new_thread(self.threadhelp, ())
        
    #funkce na zobrazeni zpravy dne