本文整理汇总了Python中thread.start_new_thread函数的典型用法代码示例。如果您正苦于以下问题:Python start_new_thread函数的具体用法?Python start_new_thread怎么用?Python start_new_thread使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了start_new_thread函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, vim, launcher, config_path):
self.config_path = os.path.abspath(config_path)
self.ensime_cache = os.path.join(os.path.dirname(self.config_path), ".ensime_cache")
self.launcher = launcher
self.log("__init__: in")
self.call_id = 0
self.browse = False
self.split = False
self.vim = vim
self.receive_callbacks = {}
self.matches = []
self.errors = []
self.vim.command("highlight EnError ctermbg=red gui=underline")
if not self.vim.eval("exists(\"g:EnErrorStyle\")"):
self.vim.command("let g:EnErrorStyle='EnError'")
self.suggests = None
self.ensime = None
self.no_teardown = False
self.open_definition = False
self.en_format_source_id = None
self.debug_thread_id = None
self.ws = None
self.queue = Queue.Queue()
self.complete_timeout = 20
thread.start_new_thread(self.unqueue_poll, ())
示例2: newtask
def newtask(self):
with self.running_mutex:
self.next_ident += 1
verbose_print("creating task %s" % self.next_ident)
thread.start_new_thread(self.task, (self.next_ident,))
self.created += 1
self.running += 1
示例3: unzip
def unzip(self, apkpath):
apkpath = unicode(apkpath, "utf8")
cmd = "tool\\7z.exe x %s -y -o%s *.dex AndroidManifest.xml lib META-INF assets"
print cmd % (apkpath, self.unpackDir)
self.ui.progressBar.setMaximum(29)
thread.start_new_thread(self.probar_thread, (3, 30))
os.system(cmd % (apkpath, self.unpackDir))
示例4: _new_thread
def _new_thread(func, *args):
global TID
tid.acquire(); id = TID = TID+1; tid.release()
io.acquire(); alive.append(id); \
print 'starting thread', id, '--', len(alive), 'alive'; \
io.release()
thread.start_new_thread( func, (id,) + args )
示例5: start
def start(self, HOST, PORT):
self.connection.connect((HOST, PORT))
print "Connected to server, please log in"
thread.start_new_thread(self.receive_messages, ())
while True:
data = raw_input()
if self.username == "" or data == "":
break
if data == REQUESTUSERNAME:
print self.username
continue
if data == LOGIN:
if self.username is None:
requestedUsername = raw_input("Please enter desired username: ")
data_dict = {REQUEST: data, USERNAME: requestedUsername}
else:
print "You are already logged in as [" + self.username + "]"
continue
elif data == LOGOUT:
data_dict = {REQUEST: data}
elif data == BACKLOG:
data_dict = {REQUEST: data}
else:
data_dict = {REQUEST: MESSAGE, MESSAGE: data}
data_dict[SENDER] = self.username
self.connection.sendall(json.dumps(data_dict))
示例6: game_next_level
def game_next_level(self):
"""
Next Levels
if the current level is not the last one(NO.10),then,enter the next level
otherwise,popup a window,on which give a hint that the player have success
this difficulty,then over the game,waiting for player to choose another difficulty.
"""
# TODO: change background image
self.timer.Stop()
if self.game.game_next_level():
thread.start_new_thread(self.playGameSound, ("Win.wav",))
self.get_back()
if self.cardback_choice >= 5:
self.cardback_choice = 0
else:
self.cardback_choice += 1
self.redraw_images()
self.refresh_top()
self.ui_point1 = wx.Point(-1, -1)
self.ui_point2 = wx.Point(-1, -1)
self.progress_timeout(9999)
self.refresh_top()
self.timer.Start()
else:
self.game_over(True)
示例7: attaqueJeu
def attaqueJeu(j="A",rep="0"):
#
# Phase attaque
# Fonction appelee en boucle a chaque coup jusqu a la fin de la partie
# Reponse : 0(rate) / 1(touche) / 2(coule) / A(fin A gagne) / B(fin B gagne)
#
global pseu, fe, popAttaque
print "feu non de dieu"
if rep=="A" or rep=="B":
# FIN PARTIE
popAttaque = Frame(root)
if rep==pseu[2]:
t = "J'ai gagn\xE9 ! Fin de la partie"
co = "green"
else:
t = "J'ai perdu ! Fin de la partie"
co = "blue"
Label(popAttaque, text=t, bg=co).pack(side=LEFT)
popAttaque.pack()
popAttaque.place(x=10, y=10) # positionnement dans la fenetre (par dessus) et non en supplement en bas
elif j==pseu[2]:
# a moi de jouer
popAttaque = Frame(root)
Label(popAttaque, text="A vous de jouer", bg="blue").pack(side=LEFT)
popAttaque.pack()
popAttaque.place(x=10, y=10) # positionnement dans la fenetre (par dessus) et non en supplement en bas
fe.bind('<Button-1>', clicFeu)
else:
# A l autre de jouer
popAttaque = Frame(root)
popAttaque.pack()
thread.start_new_thread(autreFeu,(pseu,)) # autreAttaque appelee en asynchrone
示例8: dispatch
def dispatch(input, kind, func, args, autohelp=False):
for sieve, in bot.plugs['sieve']:
input = do_sieve(sieve, bot, input, func, kind, args)
if input == None:
return
if autohelp and args.get('autohelp', True) and not input.inp \
and func.__doc__ is not None:
input.reply(func.__doc__)
return
if hasattr(func, '_apikeys'):
bot_keys = bot.config.get('api_keys', {})
keys = {key: bot_keys.get(key) for key in func._apikeys}
missing = [keyname for keyname, value in keys.items() if value is None]
if missing:
input.reply('error: missing api keys - {}'.format(missing))
return
# Return a single key as just the value, and multiple keys as a dict.
if len(keys) == 1:
input.api_key = keys.values()[0]
else:
input.api_key = keys
if func._thread:
bot.threads[func].put(input)
else:
thread.start_new_thread(run, (func, input))
示例9: run
def run(self):
"""
"""
global _Quit
# Create Socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((self.host, self.port))
# Listen for connection
sock.listen(2)
_Quit_Lock.acquire()
done = _Quit
_Quit_Lock.release()
while not done:
conn, addr = sock.accept()
logger.write_line('Hidden: Got connection from %s' % str(addr))
#print 'got input from ' + self.name
connstream = ssl.wrap_socket(conn, certfile = 'cert.pem', server_side = True)
thread.start_new_thread(self.handleInput, (connstream, ))
time.sleep(0.05)
_Quit_Lock.acquire()
done = _Quit
_Quit_Lock.release()
示例10: handle
def handle(self, addrport="", *args, **options):
if not addrport:
self.addr = ''
self.port = DEFAULT_PORT
else:
m = match(naiveip_re, addrport)
if m is None:
raise CommandError('"%s" is not a valid port number '
'or address:port pair.' % addrport)
self.addr, _, _, _, self.port = m.groups()
# Make the port available here for the path:
# socketio_tags.socketio ->
# socketio_scripts.html ->
# io.Socket JS constructor
# allowing the port to be set as the client-side default there.
environ["DJANGO_SOCKETIO_PORT"] = str(self.port)
start_new_thread(reload_watcher, ())
try:
bind = (self.addr, int(self.port))
print
print "SocketIOServer running on %s:%s" % bind
print
handler = self.get_handler(*args, **options)
server = SocketIOServer(bind, handler, resource="socket.io", policy_server=True)
server.serve_forever()
except KeyboardInterrupt:
if RELOAD:
server.stop()
print "Reloading..."
restart_with_reloader()
else:
raise
示例11: display_background
def display_background(self):
"Display a graph page in a background thread."
try:
import thread
thread.start_new_thread(self.display, ())
except ImportError:
self.display()
示例12: python_reloader
def python_reloader(main_func, args, kwargs, check_in_thread=True):
"""
If ``check_in_thread`` is False, ``main_func`` will be run in a separate
thread, and the code checker in the main thread. This was the original
behavior of this module: I (Michael Elsdoerfer) changed the default
to be the reverse: Code checker in thread, main func in main thread.
This was necessary to make the thing work with Twisted
(http://twistedmatrix.com/trac/ticket/4072).
"""
if os.environ.get("RUN_MAIN") == "true":
if check_in_thread:
thread.start_new_thread(reloader_thread, (), {"softexit": False})
else:
thread.start_new_thread(main_func, args, kwargs)
try:
if not check_in_thread:
reloader_thread(softexit=True)
else:
main_func(*args, **kwargs)
except KeyboardInterrupt:
pass
else:
try:
sys.exit(restart_with_reloader())
except KeyboardInterrupt:
pass
示例13: reloader_run
def reloader_run(server, app, interval):
if os.environ.get('BOTTLE_CHILD') == 'true':
# We are a child process
files = dict()
for module in 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.iteritems():
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)
示例14: __init__
def __init__(self):
printc("Setting up DMCS...")
self._options = "\
1 - (READY) Send Job Information\n\
2 - (SET) Send Standby Message\n\
3 - (GO) Send Readout Message\n\
4 - (RESET) Cancel a Job\n\
0 - (EXIT) Quit DMCS Simulator\n"
self._broker_url = 'amqp://' + AMQP_DMCS_USER + ':' + AMQP_DMCS_PSWD + '@' + AMQP_BROKER_ADDR + ':' + AMQP_BROKER_PORT + '/' + AMQP_BROKER_VHOST
printc('Using broker url: %s' % self._broker_url)
printc("Declaring and binding exchanges...")
printc("Attempting to create a consumer for the '%s' queue." % (Q_DMCS_CONSUME))
self._dmcs_consumer = Consumer(self._broker_url, Q_DMCS_CONSUME)
try:
printc("Attempting to start the consumer thread...")
thread.start_new_thread(self.run_dmcs_consumer, ())
except:
printc("Failed to start consumer thread, quitting...")
sys.exit()
printc("Done setting up consumer thread.")
printc("Setting up publisher...")
self._publisher = SimplePublisher(self._broker_url)
printc("Done creating publisher.")
self._job_msg = {}
self._job_msg['MSG_TYPE'] = 'JOB'
self._job_msg['JOB_NUM'] = 0
self._job_msg['RAFT_NUM'] = 1
self._standby_msg = {}
self._standby_msg['MSG_TYPE'] = 'STANDBY'
self._readout_msg = {}
self._readout_msg['MSG_TYPE'] = 'READOUT'
self._stop_msg = {}
self._stop_msg['MSG_TYPE'] = 'CANCEL'
self._shutdown_msg = {}
self._shutdown_msg['MSG_TYPE'] = 'SHUTDOWN'
示例15: test_manual_locking
def test_manual_locking(self):
import thread, os, imp, time, sys
f = open(os.path.join(self.tmpdir, 'foobaz2.py'), 'w')
f.close() # empty
done = []
def f():
sys.path.insert(0, self.tmpdir)
import foobaz2
p = sys.path.pop(0)
assert p == self.tmpdir
done.append(1)
assert not imp.lock_held()
imp.acquire_lock()
assert imp.lock_held()
thread.start_new_thread(f, ())
time.sleep(0.9)
assert not done
assert imp.lock_held()
# check that it's a recursive lock
imp.acquire_lock()
assert imp.lock_held()
imp.acquire_lock()
assert imp.lock_held()
imp.release_lock()
assert imp.lock_held()
imp.release_lock()
assert imp.lock_held()
imp.release_lock()
assert not imp.lock_held()
self.waitfor(lambda: done)
assert done