本文整理汇总了Python中thread.start函数的典型用法代码示例。如果您正苦于以下问题:Python start函数的具体用法?Python start怎么用?Python start使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了start函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: release
def release():
global released
global sortBy
global firstRun
#id: 2436312686824190668
#pokemon_id: EEVEE
#cp: 46
#stamina: 19
#stamina_max: 19
#move_1: TACKLE_FAST
#move_2: DIG
#height_m: 0.297532558441
#weight_kg: 8.24643802643
#individual_attack: 15
#individual_defense: 12
#individual_stamina: 9
#cp_multiplier: 0.166397869587
#pokeball: ITEM_POKE_BALL
#captured_cell_id: 6108423709528162304
#creation_time_ms: 1469364470778
pokeID = request.args.get('pokeID', 0)
action = request.args.get('action',0)
sortBy = request.args.get('sortBy',0)
thread = threading.Thread(target=doReleasing, args=(pokeID,action,sortBy))
thread.start()
return render_template('inventoryTimeout.html')
示例2: main
def main():
logger = logging.getLogger('default')
logger.setLevel(logging.CRITICAL)
tracks = getTrackDocuments()
print 'Found %d tracks with no POIs' % len(tracks)
workQueue = Queue.Queue()
resultQueue = Queue.Queue()
for track in tracks:
workQueue.put(track)
threads = []
for i in range(NUM_THREAD_WORKER):
thread = SparqlThread(time.time(), len(tracks), workQueue, resultQueue)
thread.setDaemon(True)
threads.append(thread)
thread.start()
writer = WriterThread(resultQueue, threads)
writer.setDaemon(True)
writer.start()
while len(threads) > 0:
try:
threads = [t.join(1000) for t in threads if t is not None and t.isAlive]
except KeyboardInterrupt:
print 'Abort'
break
示例3: dowloader
def dowloader(self, dm_list):
semaphore = threading.Semaphore(FC().amount_dm_threads)
while True:
#self.navigation.use_filter()
semaphore.acquire()
bean = dm_list.get_next_bean_to_dowload()
if bean:
if not bean.path or not self.controls.check_path(bean.path):
vk = self.controls.vk_service.find_one_track(bean.get_display_name())
if not vk:
bean.status = DOWNLOAD_STATUS_ERROR
dm_list.update_bean_info(bean)
logging.debug("Source for song not found" + bean.text)
semaphore.release()
continue
bean.path = vk.path
def notify_finish():
self.navigation.update_statistics()
semaphore.release()
thread = Dowloader(dm_list.update_bean_info, bean, notify_finish)
thread.start()
else:
time.sleep(1)
semaphore.release()
示例4: runThreads
def runThreads(numThreads, threadFunction, cleanupFunction=None, forwardException=True, threadChoice=False, startThreadMsg=True):
threads = []
kb.multiThreadMode = True
kb.threadContinue = True
kb.threadException = False
if threadChoice and numThreads == 1 and not (kb.injection.data and not any(_ not in (PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED) for _ in kb.injection.data)):
while True:
message = "please enter number of threads? [Enter for %d (current)] " % numThreads
choice = readInput(message, default=str(numThreads))
if choice:
skipThreadCheck = False
if choice.endswith('!'):
choice = choice[:-1]
skipThreadCheck = True
if choice.isdigit():
if int(choice) > MAX_NUMBER_OF_THREADS and not skipThreadCheck:
errMsg = "maximum number of used threads is %d avoiding potential connection issues" % MAX_NUMBER_OF_THREADS
logger.critical(errMsg)
else:
conf.threads = numThreads = int(choice)
break
if numThreads == 1:
warnMsg = "running in a single-thread mode. This could take a while"
logger.warn(warnMsg)
try:
if numThreads > 1:
if startThreadMsg:
infoMsg = "starting %d threads" % numThreads
logger.info(infoMsg)
else:
threadFunction()
return
# Start the threads
for numThread in xrange(numThreads):
thread = threading.Thread(target=exceptionHandledFunction, name=str(numThread), args=[threadFunction])
setDaemon(thread)
try:
thread.start()
except thread.error, ex:
errMsg = "error occurred while starting new thread ('%s')" % ex.message
logger.critical(errMsg)
break
threads.append(thread)
# And wait for them to all finish
alive = True
while alive:
alive = False
for thread in threads:
if thread.isAlive():
alive = True
time.sleep(0.1)
示例5: GetRemoteTasklets
def GetRemoteTasklets(callables):
"""Get a non-scheduled tasklet on a remote thread"""
import threading
c = stackless.channel()
def tfunc():
# thread func. Create a tasklet, remove it, and send it to the master.
# then wait for the tasklet to finish.
try:
c2 = stackless.channel()
tasklets = []
for callable in callables:
def helper(callable):
try:
callable()
except:
c2.send_throw(*sys.exc_info())
else:
c2.send(None)
t = stackless.tasklet(helper)(callable)
t.remove()
tasklets.append(t)
c.send(tasklets)
except:
c.send_throw(*sys.exc_info())
stackless.__reduce__()
for callable in callables:
c2.receive()
stackless.run() #drain the scheduler
thread = threading.Thread(target=tfunc)
thread.start()
d = c.receive(), thread
return d
示例6: run
def run(self):
self.open_socket()
input = [self.server,]
running = 1
#start a daemon thread to listen threshold
thread = Thread(target = thresholdListen, args = ())
thread.start()
#start a thread to listen results of req from masters
resultThread = Thread(target = receiveStatus, args = ())
resultThread.start()
while running:
inputready,outputready,exceptready = select.select(input,[],[])
for s in inputready:
if s == self.server:
client,address = self.server.accept()
#Assign one thread to handle each client.
self.pool.apply_async(run, args=(client,address))
else:
junk = sys.stdin.readline()
running = 0
self.server.close()
示例7: checkTimeOutPut
def checkTimeOutPut(args):
t = None
global currCommandProcess
global stde
global stdo
stde = None
stdo = None
def executeCommand():
global currCommandProcess
global stdo
global stde
try:
stdo, stde = currCommandProcess.communicate()
printLog('stdout:\n'+str(stdo))
printLog('stderr:\n'+str(stde))
except:
printLog("ERROR: UNKNOWN Exception - +checkWinTimeOutPut()::executeCommand()")
currCommandProcess = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True)
thread = Thread(target=executeCommand)
thread.start()
thread.join(TIMOUT_VAL) #wait for the thread to complete
if thread.is_alive():
printLog('ERROR: Killing the process - terminating thread because it is taking too much of time to execute')
currCommandProcess.kill()
printLog('ERROR: Timed out exception')
raise errorHandler.ApplicationException(__file__, errorHandler.TIME_OUT)
if stdo == "" or stdo==None:
errCode = currCommandProcess.poll()
printLog('ERROR: @@@@@Raising Called processor exception')
raise subprocess.CalledProcessError(errCode, args, output=stde)
return stdo
示例8: calculateAverage
def calculateAverage(period, classname):
now = datetime.datetime.utcnow().replace(tzinfo=utc)
round_now = now - datetime.timedelta(seconds=now.second, microseconds=now.microsecond)
for server in Server.objects.all().select_related():
try:
threads = []
for probe in server.probes.exclude(graph_type__name__in=['text']):
thread = threading.Thread(target=calculateAveragesForPeriod, args=[period, classname, server, probe], name="SkwisshAverage.%s.%s" % (classname.__name__, probe.display_name.encode('utf-8').replace(" ", "_")))
thread.setDaemon(False)
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
end = datetime.datetime.utcnow().replace(tzinfo=utc)
total_time = end - now
duration = float(int((total_time.seconds * 1000000) + total_time.microseconds) / 1000000.0)
success = True
message = "Calculated averages values for last %d minutes (server %s)" % (period, server.hostname)
except:
success = False
message = traceback.format_exc()
CronLog.objects.create(timestamp=round_now, action="average %dmin" % period, server=server, success=success, duration=duration, message=message)
示例9: __startThread
def __startThread(self):
self.lock.acquire()
self.threadId += 1
self.lock.release()
thread=Thread(target=self.__thread, args=[self.threadId,])
thread.daemon=True;
thread.start()
示例10: start
def start(self, ip, port):
# Set up server socket
serversocket = socketlib.socket(socketlib.AF_INET, socketlib.SOCK_STREAM)
serversocket.setsockopt(socketlib.SOL_SOCKET, socketlib.SO_REUSEADDR, 1)
serversocket.bind((ip, int(port)))
serversocket.listen(10)
serversocket.settimeout(1)
# On start!
self.onStart()
# Main connection loop
threads = []
while self.isRunning():
try:
(socket, address) = serversocket.accept()
thread = threading.Thread(target = self, args = (socket,))
threads.append(thread)
thread.start()
except socketlib.timeout:
pass
except:
self.stop()
# Wait for all threads
while len(threads):
threads.pop().join()
# On stop!
self.onStop()
示例11: get_image_from_url
def get_image_from_url( self, url, callback_pixbuf=None, callback_status=None, callback_finished=None, cover_file=None):
if not url and not os.path.exists( cover_file):
return
args=( url, callback_pixbuf, callback_status, callback_finished, cover_file )
thread=threading.Thread( target=self.image_download_thread, args=args)
thread.start()
示例12: idle
def idle(self):
# The main thread lives here and empties the
# serial buffer of data from the Arduino
# time.sleep(.1)
thread = threading.Thread(target=self.read_serial_panel)#, args=(serial_port,)
thread.start()
self.read_serial_motor()
示例13: scrape
def scrape(self):
self.threads=[]
self.LList=[]
tic=time.time()
response=requests.get(self.artist_URL, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) \
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36'})
soup=BeautifulSoup(response.text,'lxml')
header=soup.select(".results_header")
numSongs=header[0].text.split()[0]
if numSongs.strip()=="Results":
return []
if int(numSongs) > 20000:
return []
#Genius.com lists 20 songs per page
numPages=int(numSongs)/20
self.pages=numPages
for page in range(1,numPages):
URL=self.BASE_QUERY+str(page)+"&q="+self.artist
thread=pageThread(page,URL,self.artistString,self.LList)
thread.start()
self.threads.append(thread)
#Wait for all threads to finish collecting lyrics
before=0
while threading.activeCount()>3:
if threading.activeCount()!=before:
print "active count is {0}".format(threading.activeCount())
before=threading.activeCount()
for t in self.threads:
t.join()
toc=time.time()
print toc-tic,'s'
return self.LList
示例14: probeHosts
def probeHosts(hosts, numThreads=1, urlFormat=False):
global qlock, qhosts, threads, exitFlag
# add to queue
# spawn workers
for tid in range(1, numThreads+1):
#thread = ProbeThread(tid, qhosts, urlFormat)
debug("Starting Thread-{}".format(tid))
thread = threading.Thread(target=process_requests, args=(tid, urlFormat,))
thread.start()
threads.append(thread)
qlock.acquire()
for h in hosts:
qhosts.put(h)
qlock.release()
try:
# wait
while not qhosts.empty():
time.sleep(.1)
exitFlag = True
except KeyboardInterrupt:
exitFlag = True
debug("All hosts completed. Should exit now...")
# Wait for all threads to complete
for t in threads:
t.join()
示例15: _threadedLaunch
def _threadedLaunch(self, script, paramList, token):
"""this is pretty easy to merge: just think about the right
point to parameterize."""
launch = lambda : self._launchScript(script, paramList, token)
update = lambda x: x
thread = LaunchThread(launch, update)
thread.start()
return