多线程编程(2)
目前Python的lib中对多线程编程提供两种启动方法,一种是比较基本的thread模块中start_new_thread方法,在线程中运行一个函数, 另一种是使用集成threading模块的线程对象Thread类。
目前所用到的,是旧版本中调用thread模块中的start_new_thread()函数来产生新的线程
相比而言,thread.start_new_thread(function,(args[,kwargs]))实现机制其实与C更为类似,其中
function参数是将要调用的线程函数;(args[,kwargs])是将传递给待创建线程函数的参数组成的元组类型,其中kwargs是可选的参
数。新创建的线程结束一般依靠线程函数的执行结束自动退出,或者在线程函数中调用thread.exit()抛出SystemExit
exception, 达到线程退出的目的。
- print "=======================thread.start_new_thread启动线程============="
- import thread
-
- import time
- def inthread(no,interval):
- count=0
- while count<10:
- print "Thread-%d,休眠间隔:%d,current Time:%s"%(no,interval,time.ctime())
-
- time.sleep(interval)
-
- count+=1
- else:
- print "Thread-%d is over"%no
-
- thread.exit_thread()
-
- thread.start_new_thread(inthread,(1,2))
-
-
- time.sleep(30)
- '''
使用这种方法启动线程时,有可能出现异常
Unhandled exception in thread started by
Error in sys.excepthook:
Original exception was:
解决:启动线程之后,须确保主线程等待所有子线程返回结果后再退出,如果主线程比子线程早结束,无论其子线程是否是后台线程,都将会中断,抛出这个异常
若没有响应阻塞等待,为避免主线程提前退出,必须调用time.sleep使主线程休眠足够长的时间,另外也可以采用加锁机制来避免类似情况,通过在启动线程的时候,给每个线程都加了一把锁,直到线程运行介绍,再释放这个锁。同时在Python的main线程中用一个while循环来不停的判断每个线程锁已释放。
- import thread;
- from time import sleep,ctime;
- from random import choice
-
-
-
- def loop(nloop,sec,lock):
- print "Thread ",nloop," start and will sleep ",sec;
- sleep(sec);
- print "Thread ",nloop," 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();
阅读(620) | 评论(0) | 转发(0) |