Chinaunix首页 | 论坛 | 博客
  • 博客访问: 47049
  • 博文数量: 23
  • 博客积分: 425
  • 博客等级: 下士
  • 技术积分: 237
  • 用 户 组: 普通用户
  • 注册时间: 2012-12-10 09:57
文章分类

全部博文(23)

文章存档

2013年(23)

我的朋友

分类: Python/Ruby

2013-01-05 19:10:47

多线程编程(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, 达到线程退出的目的。

  1. print "=======================thread.start_new_thread启动线程============="    
  2. import thread    
  3. #Python的线程sleep方法并不是在thread模块中,反而是在time模块下    
  4. import time    
  5. def inthread(no,interval):    
  6.     count=0    
  7.     while count<10:    
  8.         print "Thread-%d,休眠间隔:%d,current Time:%s"%(no,interval,time.ctime())    
  9.         #使当前线程休眠指定时间,interval为浮点型的秒数,不同于Java中的整形毫秒数    
  10.         time.sleep(interval)    
  11.         #Python不像大多数高级语言一样支持++操作符,只能用+=实现    
  12.         count+=1    
  13.     else:    
  14.         print "Thread-%d is over"%no    
  15.         #可以等待线程被PVM回收,或主动调用exit或exit_thread方法结束线程    
  16.         thread.exit_thread()    
  17. #使用start_new_thread函数可以简单的启动一个线程,第一个参数指定线程中执行的函数,第二个参数为元组型的传递给指定函数的参数值    
  18. thread.start_new_thread(inthread,(1,2))    
  19.     #线程执行时必须添加这一行,并且sleep的时间必须足够使线程结束,如本例    
  20.     #如果休眠时间改为20,将可能会抛出异常    
  21. time.sleep(30)    
  22. '''    
使用这种方法启动线程时,有可能出现异常

Unhandled exception in thread started by
Error in sys.excepthook:
Original exception was:
解决:启动线程之后,须确保主线程等待所有子线程返回结果后再退出,如果主线程比子线程早结束,无论其子线程是否是后台线程,都将会中断,抛出这个异常
            若没有响应阻塞等待,为避免主线程提前退出,必须调用time.sleep使主线程休眠足够长的时间,另外也可以采用加锁机制来避免类似情况,通过在启动线程的时候,给每个线程都加了一把锁,直到线程运行介绍,再释放这个锁。同时在Python的main线程中用一个while循环来不停的判断每个线程锁已释放

  1. import thread;    
  2. from time import sleep,ctime;    
  3. from random import choice    
  4. #The first param means the thread number    
  5. #The second param means how long it sleep    
  6. #The third param means the Lock    
  7. def loop(nloop,sec,lock):    
  8.     print "Thread ",nloop," start and will sleep ",sec;    
  9.     sleep(sec);    
  10.     print "Thread ",nloop," end  ",sec;    
  11.     lock.release();    
  12.     
  13. def main():    
  14.     seconds=[4,2];    
  15.     locks=[];    
  16.     for i in range(len(seconds)) :    
  17.         lock=thread.allocate_lock();    
  18.         lock.acquire();    
  19.         locks.append(lock);    
  20.             
  21.     print "main Thread begins:",ctime();    
  22.     for i,lock in enumerate(locks):    
  23.         thread.start_new_thread(loop,(i,choice(seconds),lock));    
  24.     for lock in locks :    
  25.         while lock.locked() :     
  26.             pass;    
  27.     print "main Thread ends:",ctime();    
  28.     
  29. if __name__=="__main__" :    
  30.     main();   
阅读(620) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~