Python中多线程的创建及基本调用方法
1. 多线程的作用 2. Python中的多线程相关模块和方法 3.示例 print "=======================thread.start_new_thread启动线程=============" import thread #Python的线程sleep方法并不是在thread模块中,反而是在time模块下 import time def inthread(no,interval): count=0 while count<10: print "Thread-%d,休眠间隔:%d,current Time:%s"%(no,interval,time.ctime()) #使当前线程休眠指定时间,interval为浮点型的秒数,不同于Java中的整形毫秒数 time.sleep(interval) #Python不像大多数高级语言一样支持++操作符,只能用+=实现 count+=1 else: print "Thread-%d is over"%no #可以等待线程被PVM回收,或主动调用exit或exit_thread方法结束线程 thread.exit_thread() #使用start_new_thread函数可以简单的启动一个线程,第一个参数指定线程中执行的函数,第二个参数为元组型的传递给指定函数的参数值 thread.start_new_thread(inthread,(1,2)) #线程执行时必须添加这一行,并且sleep的时间必须足够使线程结束,如本例 #如果休眠时间改为20,将可能会抛出异常 time.sleep(30) ''' 使用这种方法启动线程时,有可能出现异常 Unhandled exception in thread started by Error in sys.excepthook: Original exception was: 解决:启动线程之后,须确保主线程等待所有子线程返回结果后再退出,如果主线程比子线程早结束,无论其子线程是否是后台线程,都将会中断,抛出这个异常 import thread; from time import sleep,ctime; from random import choice #The first param means the thread number #The second param means how long it sleep #The third param means the Lock def loop(nloop,sec,lock): print "Thread ",nloop," start and will sleep ",sec; sleep(sec); print "Thread "," end ",sec; lock.release(); def main(): seconds=[4,2]; locks=[]; for i in range(len(seconds)) : lock=thread.allocate_lock(); lock.acquire(); locks.append(lock); print "main Thread begins:",ctime(); for i,lock in enumerate(locks): thread.start_new_thread(loop,(i,choice(seconds),lock)); for lock in locks : while lock.locked() : pass; print "main Thread ends:",ctime(); if __name__=="__main__" : main(); 很多介绍说在新python版本中推荐使用Threading模块,目前暂没有应用到。。。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |