本文整理汇总了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: knock
# 需要导入模块: import thread [as 别名]
# 或者: from thread import start_new_thread [as 别名]
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)
示例2: StartListener
# 需要导入模块: import thread [as 别名]
# 或者: from thread import start_new_thread [as 别名]
def StartListener(forwardingURL, localAddress, localPort, destAddress, destPort):
#formattedAddress = str(localAddress) + ":" + str(localPort)
formattedAddress = '%s:%s' % (localAddress, localPort)
try:
myserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
myserver.bind((localAddress, localPort))
myserver.listen(2)
#outputHandler.outputMessage('Server started')
outputHandler.outputMessage('Listener ready to forward connections from %s to %s:%i via %s' % (formattedAddress, destAddress, destPort, forwardingURL))
while runServer > 0:
try:
outputHandler.outputMessage('Waiting for client connection to %s' % (formattedAddress))
client, addr = myserver.accept()
outputHandler.outputMessage('Client connected to %s' %(formattedAddress))
thread.start_new_thread(child, (client, addr, formattedAddress, forwardingURL, destAddress, destPort))
except Exception as e:
if "Closing connections" not in str(e):
raise e
except Exception as e:
outputHandler.outputMessage('Error in listener on %s: %s' % (formattedAddress, e))
outputHandler.outputMessage('Shutting down listener on %s' % (formattedAddress))
示例3: handle_event
# 需要导入模块: import thread [as 别名]
# 或者: from thread import start_new_thread [as 别名]
def handle_event(self, event, sender, level, formatted_msg, data):
if self.dbot is None:
try:
self.bot.logger.info("Discord bot not running, Starting..")
self.dbot = DiscordClass(self.bot, self.master, self.pokemons, self.config)
self.dbot.connect()
thread.start_new_thread(self.dbot.run)
except Exception as inst:
self.dbot = None
self.bot.logger.error("Unable to start Discord bot; master: {}, exception: {}".format(self.master, pprint.pformat(inst)))
return
# prepare message to send
msg = None
msg = self.chat_handler.get_event(event, formatted_msg, data)
if msg:
self.dbot.sendMessage(to=self.master, text=msg)
示例4: create_desktop
# 需要导入模块: import thread [as 别名]
# 或者: from thread import start_new_thread [as 别名]
def create_desktop(desktop_name, start_explorer=1):
""" Creates a new desktop and spawns a thread running on it
Will also start a new icon thread on an existing desktop
"""
sa=pywintypes.SECURITY_ATTRIBUTES()
sa.bInheritHandle=1
try:
hdesk=win32service.CreateDesktop(desktop_name, 0, win32con.MAXIMUM_ALLOWED, sa)
except win32service.error:
traceback.print_exc()
errbuf=cStringIO.StringIO()
traceback.print_exc(None,errbuf)
win32api.MessageBox(0, errbuf.getvalue(), 'Desktop creation failed')
return
if start_explorer:
s=win32process.STARTUPINFO()
s.lpDesktop=desktop_name
prc_info=win32process.CreateProcess(None, "Explorer.exe",None,None,True,win32con.CREATE_NEW_CONSOLE,None,'c:\\',s)
th=thread.start_new_thread(new_icon,(hdesk,desktop_name))
hdesk.SwitchDesktop()
示例5: _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)
# 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()
示例6: test_foreign_thread
# 需要导入模块: import thread [as 别名]
# 或者: from thread import start_new_thread [as 别名]
def test_foreign_thread(self):
# Check that a "foreign" thread can use the threading module.
def f(mutex):
# Calling current_thread() forces an entry for the foreign
# thread to get made in the threading._active map.
threading.current_thread()
mutex.release()
mutex = threading.Lock()
mutex.acquire()
tid = thread.start_new_thread(f, (mutex,))
# Wait for the thread to finish.
mutex.acquire()
self.assertIn(tid, threading._active)
self.assertIsInstance(threading._active[tid], threading._DummyThread)
del threading._active[tid]
# PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
# exposed at the Python level. This test relies on ctypes to get at it.
示例7: 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, '')
self.assertEqual(err, '')
示例8: test_makefile_refcount
# 需要导入模块: import thread [as 别名]
# 或者: from thread import start_new_thread [as 别名]
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)
示例9: test_stack_size
# 需要导入模块: import thread [as 别名]
# 或者: from thread import start_new_thread [as 别名]
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)
示例10: starter
# 需要导入模块: import thread [as 别名]
# 或者: from thread import start_new_thread [as 别名]
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, ())
示例11: handle_error
# 需要导入模块: import thread [as 别名]
# 或者: from thread import start_new_thread [as 别名]
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,))
示例12: test_start_new_thread
# 需要导入模块: import thread [as 别名]
# 或者: from thread import start_new_thread [as 别名]
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()
示例13: 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]
示例14: _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]
示例15: 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]