本文整理汇总了Python中_thread.start_new_thread方法的典型用法代码示例。如果您正苦于以下问题:Python _thread.start_new_thread方法的具体用法?Python _thread.start_new_thread怎么用?Python _thread.start_new_thread使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类_thread
的用法示例。
在下文中一共展示了_thread.start_new_thread方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _run_in_multiple_threads
# 需要导入模块: import _thread [as 别名]
# 或者: from _thread import start_new_thread [as 别名]
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]
示例2: speak
# 需要导入模块: import _thread [as 别名]
# 或者: from _thread import start_new_thread [as 别名]
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
示例3: on_release
# 需要导入模块: import _thread [as 别名]
# 或者: from _thread import start_new_thread [as 别名]
def on_release(key):
global combo_vk
if isinstance(key, Key):
print('Key:', key.name, key.value.vk)
vk = key.value.vk
elif isinstance(key, KeyCode):
print('KeyCode:', key.char, key.vk)
vk = key.vk
else:
assert False
if vk == combo_vk:
return
_thread.start_new_thread(combo_press, (vk, ))
示例4: python_reloader
# 需要导入模块: import _thread [as 别名]
# 或者: from _thread import start_new_thread [as 别名]
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
示例5: test_init_once_multithread
# 需要导入模块: import _thread [as 别名]
# 或者: from _thread import start_new_thread [as 别名]
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]
示例6: test_init_once_multithread
# 需要导入模块: import _thread [as 别名]
# 或者: from _thread import start_new_thread [as 别名]
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]
示例7: test_init_once_multithread_failure
# 需要导入模块: import _thread [as 别名]
# 或者: from _thread import start_new_thread [as 别名]
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
示例8: start_serving
# 需要导入模块: import _thread [as 别名]
# 或者: from _thread import start_new_thread [as 别名]
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, ())
示例9: _setUp
# 需要导入模块: import _thread [as 别名]
# 或者: from _thread import start_new_thread [as 别名]
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()
示例10: _setUp
# 需要导入模块: import _thread [as 别名]
# 或者: from _thread import start_new_thread [as 别名]
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()
示例11: test_dummy_thread_after_fork
# 需要导入模块: import _thread [as 别名]
# 或者: from _thread import start_new_thread [as 别名]
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'')
示例12: intercept_threads
# 需要导入模块: import _thread [as 别名]
# 或者: from _thread import start_new_thread [as 别名]
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
示例13: download_thread
# 需要导入模块: import _thread [as 别名]
# 或者: from _thread import start_new_thread [as 别名]
def download_thread(url, path, exfile_name=None, exfile_dir=None):
tag = 'Download_Thread'
wait_for_limit()
local_path = path
give_it_a_sign = False
local_filename = url.split('/')[-1]
if local_filename.endswith('zip'):
give_it_a_sign = True
if exfile_dir is not None:
local_path += exfile_dir + global_symbol
if exfile_name is not None:
local_filename = exfile_name + "-" + local_filename
path_output = local_path + local_filename
print_with_tag(tag, ["File Location:" + path_output])
if not os.path.exists(local_path):
print_with_tag(tag, "Folder doesn't exists!!")
os.makedirs(local_path)
print_with_tag(tag, "Folder Created.")
retry_count = 0
while True:
try:
_thread.TIMEOUT_MAX = 60
_thread.start_new_thread(download_file, (url, path_output, give_it_a_sign))
except:
print_with_tag(tag, "Error.")
if retry_count == 3:
print_with_tag(tag, "Not wokring..")
print_with_tag(tag, "Skip!!")
else:
print_with_tag(tag, "Starting retry..")
retry_count += 1
else:
print_with_tag(tag, "Download thread successfully started!")
break
print_with_tag(tag, ['Threads_count:', str(current_threads)])
示例14: start_new_thread
# 需要导入模块: import _thread [as 别名]
# 或者: from _thread import start_new_thread [as 别名]
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:
import traceback
traceback.print_exc()
_main = True
global _interrupt
if _interrupt:
_interrupt = False
raise KeyboardInterrupt
示例15: interrupt_main
# 需要导入模块: import _thread [as 别名]
# 或者: from _thread import start_new_thread [as 别名]
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