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: test_verify.py From SwiftKitten with MIT License | 7 votes |
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 #2
Source File: backend_tests.py From SwiftKitten with MIT License | 7 votes |
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 #3
Source File: gtk.py From encompass with GNU General Public License v3.0 | 6 votes |
def restore_wallet(self, wallet): dialog = Gtk.MessageDialog( parent = None, flags = Gtk.DialogFlags.MODAL, buttons = Gtk.ButtonsType.CANCEL, message_format = "Please wait..." ) dialog.show() def recover_thread( wallet, dialog ): wallet.restore(lambda x:x) GObject.idle_add( dialog.destroy ) thread.start_new_thread( recover_thread, ( wallet, dialog ) ) r = dialog.run() dialog.destroy() if r==Gtk.ResponseType.CANCEL: return False if not wallet.is_found(): show_message("No transactions found for this seed") return True
Example #4
Source File: test_threading.py From ironpython2 with Apache License 2.0 | 6 votes |
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, '') self.assertEqual(err, '')
Example #5
Source File: test__socket.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_makefile_refcount(self): "Ensures that the _socket stays open while there's still a file associated" def echoer(port): s = _socket.socket() s.bind(('localhost', port)) s.listen(5) (s2, ignore) = s.accept() s2.send(s2.recv(10)) port = 50008 thread.start_new_thread(echoer, (port, )) time.sleep(0) s = _socket.socket() s.connect(('localhost', port)) f1 = s.makefile('r') f2 = s.makefile('w') s.close() test_msg = 'abc\n' f2.write(test_msg) f2.flush() str = f1.readline() self.assertTrue(str==test_msg)
Example #6
Source File: test_thread.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_stack_size(self): import sys if is_cli or (sys.version_info[0] == 2 and sys.version_info[1] > 4) or sys.version_info[0] > 2: import thread size = thread.stack_size() self.assertTrue(size==0 or size>=32768) bad_size_list = [ 1, -1, -32768, -32769, -32767, -40000, 32767, 32766] for bad_size in bad_size_list: self.assertRaises(ValueError, thread.stack_size, bad_size) good_size_list = [4096*10, 4096*100, 4096*1000, 4096*10000] for good_size in good_size_list: #CodePlex Work Item 7827 if is_cli and good_size<=50000: print "Ignoring", good_size, "for CLI"; continue temp = thread.stack_size(good_size) self.assertTrue(temp>=32768 or temp==0) def temp(): pass thread.start_new_thread(temp, ()) temp = thread.stack_size(1024*1024) self.assertTrue(temp>=32768 or temp==0)
Example #7
Source File: test_sys_getframe.py From ironpython2 with Apache License 2.0 | 6 votes |
def starter(events): def tracer(*args): events.append(args[1]) return tracer def f1(): time.sleep(.25) def f2(): time.sleep(1) def f3(): time.sleep(.5) def test_thread(): global done, failed try: sys.settrace(tracer) f1() sys.settrace(None) f2() sys.settrace(tracer) f3() except: failed = True with lock: done += 1 thread.start_new_thread(test_thread, ())
Example #8
Source File: test_socket.py From BinderFilter with MIT License | 6 votes |
def _setUp(self): self.server_ready = threading.Event() self.client_ready = threading.Event() self.done = threading.Event() self.queue = Queue.Queue(1) # 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,)) self.__setUp() if not self.server_ready.is_set(): self.server_ready.set() self.client_ready.wait()
Example #9
Source File: test_threading.py From BinderFilter with MIT License | 6 votes |
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, '') self.assertEqual(err, '')
Example #10
Source File: test_socket.py From oss-ftp with MIT License | 6 votes |
def _setUp(self): self.server_ready = threading.Event() self.client_ready = threading.Event() self.done = threading.Event() self.queue = Queue.Queue(1) # 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,)) self.__setUp() if not self.server_ready.is_set(): self.server_ready.set() self.client_ready.wait()
Example #11
Source File: rtl_mus.py From rtl_mus with GNU General Public License v3.0 | 6 votes |
def handle_error(self): global server_missing_logged global rtl_tcp_connected rtl_tcp_connected=False exc_type, exc_value, exc_traceback = sys.exc_info() self.ok=False server_is_missing=hasattr(exc_value,"errno") and exc_value.errno==111 if (not server_is_missing) or (not server_missing_logged): log.error("with rtl_tcp host connection: "+str(exc_value)) #traceback.print_tb(exc_traceback) server_missing_logged|=server_is_missing try: self.close() except: pass thread.start_new_thread(rtl_tcp_asyncore_reset, (2,))
Example #12
Source File: test_additional_thread_info.py From PyDev.Debugger with Eclipse Public License 1.0 | 6 votes |
def test_start_new_thread(self): pydev_monkey.patch_thread_modules() try: found = {} def function(a, b, *args, **kwargs): found['a'] = a found['b'] = b found['args'] = args found['kwargs'] = kwargs thread.start_new_thread(function, (1,2,3,4), {'d':1, 'e':2}) import time for _i in xrange(20): if len(found) == 4: break time.sleep(.1) else: raise AssertionError('Could not get to condition before 2 seconds') self.assertEqual({'a': 1, 'b': 2, 'args': (3, 4), 'kwargs': {'e': 2, 'd': 1}}, found) finally: pydev_monkey.undo_patch_thread_modules()
Example #13
Source File: test_verify1.py From SwiftKitten with MIT License | 6 votes |
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 #14
Source File: test_ffi_obj.py From SwiftKitten with MIT License | 6 votes |
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 #15
Source File: test_ffi_obj.py From SwiftKitten with MIT License | 6 votes |
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 #16
Source File: room.py From pydouyu with MIT License | 6 votes |
def knock(self): self.client = network.client.Client() # Send AUTH request self.client.send({'type': 'loginreq','roomid': self.room_id}) # Start a thread to send KEEPALIVE messages separately thread.start_new_thread(keep_alive, (self.client, KEEP_ALIVE_INTERVAL_SECONDS)) # Handle messages for message in self.client.receive(): if not message: continue # print json.dumps(message.body) msg_type = message.attr('type') # Send JOIN_GROUP request if msg_type == 'loginres': self.client.send({'type': 'joingroup', 'rid': self.room_id, 'gid': self.channel_id}) self.trigger_callbacks(msg_type, message)
Example #17
Source File: test_threading.py From oss-ftp with MIT License | 6 votes |
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, '') self.assertEqual(err, '')
Example #18
Source File: _pydevd_test_find_main_thread_id.py From PyDev.Debugger with Eclipse Public License 1.0 | 5 votes |
def check_fix_main_thread_id_multiple_threads(): import attach_script import sys import time assert 'threading' not in sys.modules try: import thread except ImportError: import _thread as thread lock = thread.allocate_lock() lock2 = thread.allocate_lock() def method(): lock2.acquire() import threading # Note: imported on wrong thread assert threading.current_thread().ident == thread.get_ident() assert threading.current_thread() is attach_script.get_main_thread_instance(threading) attach_script.fix_main_thread_id() assert threading.current_thread().ident == thread.get_ident() assert threading.current_thread() is not attach_script.get_main_thread_instance(threading) with lock: pass # Will only finish when lock is released. with lock: thread.start_new_thread(method, ()) while not lock2.locked(): time.sleep(.1) wait_for_condition(lambda: len(sys._current_frames()) == 2) main_thread_id, log_msg = attach_script.get_main_thread_id(None) assert main_thread_id == thread.get_ident(), 'Found: %s, Expected: %s' % (main_thread_id, thread.get_ident()) assert not log_msg assert 'threading' in sys.modules import threading assert threading.current_thread().ident == main_thread_id wait_for_condition(lambda: len(sys._current_frames()) == 1)
Example #19
Source File: dummy_thread.py From Computable with MIT License | 5 votes |
def interrupt_main(): """Set _interrupt flag to True to have start_new_thread raise KeyboardInterrupt upon exiting.""" if _main: raise KeyboardInterrupt else: global _interrupt _interrupt = True
Example #20
Source File: dummy_thread.py From Computable with MIT License | 5 votes |
def start_new_thread(function, args, kwargs={}): """Dummy implementation of thread.start_new_thread(). Compatibility is maintained by making sure that ``args`` is a tuple and ``kwargs`` is a dictionary. If an exception is raised and it is SystemExit (which can be done by thread.exit()) it is caught and nothing is done; all other exceptions are printed out by using traceback.print_exc(). If the executed function calls interrupt_main the KeyboardInterrupt will be raised when the function returns. """ if type(args) != type(tuple()): raise TypeError("2nd arg must be a tuple") if type(kwargs) != type(dict()): raise TypeError("3rd arg must be a dict") global _main _main = False try: function(*args, **kwargs) except SystemExit: pass except: _traceback.print_exc() _main = True global _interrupt if _interrupt: _interrupt = False raise KeyboardInterrupt
Example #21
Source File: dummy_thread.py From meddle with MIT License | 5 votes |
def interrupt_main(): """Set _interrupt flag to True to have start_new_thread raise KeyboardInterrupt upon exiting.""" if _main: raise KeyboardInterrupt else: global _interrupt _interrupt = True
Example #22
Source File: telnetlib.py From oss-ftp with MIT License | 5 votes |
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)
Example #23
Source File: test_threading.py From oss-ftp with MIT License | 5 votes |
def test_ident_of_no_threading_threads(self): # The ident still must work for the main thread and dummy threads. self.assertFalse(threading.currentThread().ident is None) def f(): ident.append(threading.currentThread().ident) done.set() done = threading.Event() ident = [] thread.start_new_thread(f, ()) done.wait() self.assertFalse(ident[0] is None) # Kill the "immortal" _DummyThread del threading._active[ident[0]] # run with a small(ish) thread stack size (256kB)
Example #24
Source File: test_threading.py From oss-ftp with MIT License | 5 votes |
def test_finalize_runnning_thread(self): # Issue 1402: the PyGILState_Ensure / _Release functions may be called # very late on python exit: on deallocation of a running thread for # example. try: import ctypes except ImportError: self.skipTest('requires ctypes') rc = subprocess.call([sys.executable, "-c", """if 1: import ctypes, sys, time, thread # This lock is used as a simple event variable. ready = thread.allocate_lock() ready.acquire() # Module globals are cleared before __del__ is run # So we save the functions in class dict class C: ensure = ctypes.pythonapi.PyGILState_Ensure release = ctypes.pythonapi.PyGILState_Release def __del__(self): state = self.ensure() self.release(state) def waitingThread(): x = C() ready.release() time.sleep(100) thread.start_new_thread(waitingThread, ()) ready.acquire() # Be sure the other thread is waiting. sys.exit(42) """]) self.assertEqual(rc, 42)
Example #25
Source File: piano_input.py From light-my-piano with Apache License 2.0 | 5 votes |
def __init__(self): self.user_input = Queue.Queue() endpoint_address = self._attach_device() thread.start_new_thread(self.GetPianoSignal, (endpoint_address, ))
Example #26
Source File: rtl_mus.py From rtl_mus with GNU General Public License v3.0 | 5 votes |
def __init__(self): global server_missing_logged asyncore.dispatcher.__init__(self) self.ok=True self.create_socket(socket.AF_INET, socket.SOCK_STREAM) try: self.connect((cfg.rtl_tcp_host, cfg.rtl_tcp_port)) self.socket.settimeout(0.1) except: log.error("rtl_tcp connection refused. Retrying.") thread.start_new_thread(rtl_tcp_asyncore_reset, (1,)) self.close() return
Example #27
Source File: piano_input_mock.py From light-my-piano with Apache License 2.0 | 5 votes |
def __init__(self): self.user_input = Queue.Queue() thread.start_new_thread(self.GetPianoSignal, ())
Example #28
Source File: rtl_mus.py From rtl_mus with GNU General Public License v3.0 | 5 votes |
def handle_close(self): global rtl_tcp_connected global rtl_tcp_core rtl_tcp_connected=False log.error("rtl_tcp host connection has closed, now trying to reopen") try: self.close() except: pass thread.start_new_thread(rtl_tcp_asyncore_reset, (2,))
Example #29
Source File: _pydevd_test_find_main_thread_id.py From PyDev.Debugger with Eclipse Public License 1.0 | 5 votes |
def check_main_thread_id_multiple_threads(): import attach_script import sys import time assert 'threading' not in sys.modules try: import thread except ImportError: import _thread as thread lock = thread.allocate_lock() lock2 = thread.allocate_lock() def method(): lock2.acquire() with lock: pass # Will only finish when lock is released. with lock: thread.start_new_thread(method, ()) while not lock2.locked(): time.sleep(.1) wait_for_condition(lambda: len(sys._current_frames()) == 2) main_thread_id, log_msg = attach_script.get_main_thread_id(None) assert main_thread_id == thread.get_ident(), 'Found: %s, Expected: %s' % (main_thread_id, thread.get_ident()) assert not log_msg assert 'threading' not in sys.modules wait_for_condition(lambda: len(sys._current_frames()) == 1)
Example #30
Source File: main.py From seu-jwc-catcher with MIT License | 5 votes |
def submit_login(self): global username global password global vercode username = self.edit_username.get() password = self.edit_password.get() vercode = self.edit_vercode.get() root.event_generate("<<EVENT_LOGIN>>") id = thread.start_new_thread(self.init_data, (3,)) pass # 正在登录,在这里获取网络数据