thread模块
thread模块除了产生线程外,thread模块也提供了基本的同步数据结构锁对象(lock object也叫原语锁、简单锁、
互斥锁、互斥量、二值信号量)。同步原语与线程的管理是密不可分的。
常用的线程函数以及LockType类型的锁对象的方法:
1).thread.start_new_thread(function,args[,kwargs])
调用thread模块中的start_new_thread()函数来产生新线程。语法如下:
function:线程函数
args:传递给线程函数的参数,它必须是个tuple类型
如果想要运行的函数不要参数,也要传一个空的元组。
2).allocate_lock()
分配一个LockType类型的锁对象
3).exit()
让线程退出
LockType类型锁对象方法
4).acquire()
尝试获取锁对象
5).locked()
如果获取了锁对象返回True,否则返回False
6).release()
释放锁
import time
import thread
def timer(no,interval):
cnt=0
while cnt<10:
print 'Thread:(%d) Time:%s\n'%(no,time.ctime())
time.sleep(interval)
cnt+=1
thread.exit_thread()
def test():
thread.start_new_thread(timer,(1,2))
thread.start_new_thread(timer,(5,2))
if __name__=='__main__':
test()
执行结果:Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
出现此现象的原因:
启动线程之后,须确保主线程等待所有子线程返回结果后再退出,如果主线程比子线程早结束,无论其子线程
是否是后台线程,都将会中断,抛出这个异常 。
若没有响应阻塞等待,为避免主线程提前退出,必须调用time.sleep使主线程休眠足够长的时间,另外也可以
采用加锁机制来避免类似情况,通过在启动线程的时候,给每个线程都加了一把锁,直到线程运行结束,
再释放这个锁。同时在Python的main线程中用一个while循环来不停的判断每个线程锁已释放。
对上面的例子进行改进:
import time
import thread
def timer(no,interval):
cnt=0
while cnt<10:
print 'Thread:(%d) Time:%s\n'%(no,time.ctime())
time.sleep(interval)
cnt+=1
thread.exit_thread()
def test():
thread.start_new_thread(timer,(1,2))
thread.start_new_thread(timer,(5,2))
if __name__=='__main__':
test()
time.sleep(30)
执行结果:Thread:(1) Time:Tue Jun 30 17:41:11 2015
Thread:(5) Time:Tue Jun 30 17:41:11 2015
Thread:(1) Time:Tue Jun 30 17:41:13 2015
Thread:(5) Time:Tue Jun 30 17:41:13 2015
Thread:(1) Time:Tue Jun 30 17:41:15 2015
Thread:(5) Time:Tue Jun 30 17:41:15 2015
Thread:(1) Time:Tue Jun 30 17:41:17 2015
Thread:(5) Time:Tue Jun 30 17:41:17 2015
Thread:(1) Time:Tue Jun 30 17:41:19 2015
Thread:(5) Time:Tue Jun 30 17:41:19 2015
Thread:(1) Time:Tue Jun 30 17:41:21 2015
Thread:(5) Time:Tue Jun 30 17:41:21 2015
Thread:(1) Time:Tue Jun 30 17:41:23 2015
Thread:(5) Time:Tue Jun 30 17:41:23 2015
Thread:(1) Time:Tue Jun 30 17:41:25 2015
Thread:(5) Time:Tue Jun 30 17:41:25 2015
Thread:(1) Time:Tue Jun 30 17:41:27 2015
Thread:(5) Time:Tue Jun 30 17:41:27 2015
Thread:(1) Time:Tue Jun 30 17:41:29 2015
Thread:(5) Time:Tue Jun 30 17:41:29 2015
尽量不要使用Thread模块,原因大致如下:
1).更高级别的Threading模块更为先进,对线程的支持更为完善,而且使用thread模块的属性可能与Threading
出现冲突。
2).低级别的Thread模块的同步原语很少,而Threading有很多。
3).Thread对于你的进程什么时候结束完全没有控制,当主线程结束时,所有的线程都会被强制结束,没有警告
也不会有正常的清除工作,而Threading模块能够确保重要的子进程退出后才退出。
4).Thread不支持守护线程,而Threading支持。