标签:
一、异常处理
异常:因某个程序出现了错误而在正常控制流以外采取的行为。
1 while True: 2 num1 = input(‘num1:‘) 3 num2 = input(‘num2:‘) 4 try: 5 num1 = int(num1) 6 num2 = int(num2) 7 result = num1 + num2 8 except ValueError as e: 9 print(‘value err‘,e) 10 except Exception as e: 11 print(‘Error info:‘) 12 print(e)
1 class JefException(Exception): 2 def __init__(self,msg): 3 self.message = msg 4 5 def __str__(self): 6 return self.message 7 8 a = 1 9 try: 10 assert a == 1 11 #raise JefException(‘My Error‘) 12 except JefException as e: 13 print(e) 14 else: 15 print(‘hahaha else‘) 16 finally: 17 print(‘no matter right or wrong,run this anywhere‘)
二、信号量
它是进程之间通讯的方式,是一种软件中断。一个进程接收到信号就会打断原来的程序执行流程来处理信号。
1 import threading,time 2 3 def run(n): 4 semaphore.acquire() 5 time.sleep(1) 6 print("run the thread: %s\n" %n) 7 semaphore.release() 8 9 if __name__ == ‘__main__‘: 10 11 num= 0 12 semaphore = threading.BoundedSemaphore(5) #最多允许5个线程同时运行 13 for i in range(20): 14 t = threading.Thread(target=run,args=(i,)) 15 t.start() 16 17 while threading.active_count() != 1: 18 pass #print threading.active_count() 19 else: 20 print(‘----all threads done---‘) 21 print(num)
三、线程
线程运行在同一个进程当中,共享相同的运行操作环境。
线程的调用方式可以分为直接调用和继承调用两种方式。
直接调用
1 import threading 2 import time 3 4 def sayhi(num): #定义每个线程要运行的函数 5 6 print("running on number:%s" %num) 7 8 time.sleep(3) 9 10 if __name__ == ‘__main__‘: 11 ‘‘‘t1 = threading.Thread(target=sayhi,args=(1,)) #生成一个线程实例 12 t2 = threading.Thread(target=sayhi,args=(2,)) #生成另一个线程实例 13 14 t1.start() #启动线程 15 t2.start() #启动另一个线程 16 17 print(t1.getName()) #获取线程名 18 print(t2.getName()) 19 t2.join()#t2.wait 20 ‘‘‘ 21 t_list = [] 22 for i in range(10): 23 t = threading.Thread(target=sayhi,args=[i,]) 24 t.start() 25 for i in t_list: 26 i.join() 27 print(‘----main----‘)
继承调用
1 class MyThread(threading.Thread): 2 def __init__(self,num): 3 threading.Thread.__init__(self) 4 self.num = num 5 6 def run(self):#定义每个线程要运行的函数 7 8 print("running on number:%s" %self.num) 9 10 time.sleep(3) 11 12 if __name__ == ‘__main__‘: 13 14 t1 = MyThread(1) 15 t2 = MyThread(2) 16 t1.start() 17 t2.start()
daemon
1 import time 2 import threading 3 4 def run(n): 5 6 print(‘[%s]------running----\n‘ % n) 7 time.sleep(2) 8 print(‘--done--‘) 9 10 def main(): 11 for i in range(5): 12 t = threading.Thread(target=run,args=[i,]) 13 #time.sleep(1) 14 t.start() 15 #t.join(1) 16 print(‘starting thread‘, t.getName()) 17 18 19 m = threading.Thread(target=main,args=[]) 20 m.setDaemon(True) #将主线程设置为Daemon线程,它退出时,其它子线程会同时退出,不管是否执行完任务 21 m.start() 22 m.join(timeout=3) 23 print("---main thread done----")
标签:
原文地址:http://www.cnblogs.com/jef1025/p/5293605.html