Python多线程学习<转>

Python多线程学习 
一.创建线程 
1.通过thread模块中的start_new_thread(func,args)创建线程:
在Eclipse+pydev中敲出以下代码:

Python代码   收藏代码
  1. # -*- coding: utf-8 -*-   
  2. import thread    
  3. def run_thread(n):    
  4.         for i in range(n):    
  5.             print i    
  6.     
  7. thread.start_new_thread(run_thread,(4,)) #参数一定是元组,两个参数可以写成(a,b)  

 

运行报错如下:

 

Python代码   收藏代码
  1. Unhandled exception in thread started by   
  2. sys.excepthook is missing  
  3. lost sys.stderr  

 

网上查出原因是不建议使用thread,然后我在pythonGUI中做了测试,测试结果如下,显然python是支持thread创建多线程的,在pydev中出错原因暂时不明。

 

Python代码   收藏代码
  1. >>> import thread  
  2. >>> def run(n):  
  3.     for i in range(n):  
  4.         print i  
  5.   
  6. >>> thread.start_new_thread(run,(4,))  
  7. 98520  
  8.   
  9.   
  10. 1  
  11. >>>   
  12. 2  
  13. 3  

 

2.通过继承threading.Thread创建线程,以下示例创建了两个线程

Python代码   收藏代码
  1. # -*- coding: utf-8 -*-   
  2. ''''' 
  3. Created on 2012-8-8 
  4.  
  5. @author: jeromewei 
  6.  '''     
  7. from threading import Thread  
  8. import time  
  9. class race(Thread):  
  10.     def __init__(self,threadname,interval):  
  11.         Thread.__init__(self,name=threadname)  
  12.         self.interval = interval  
  13.         self.isrunning = True  
  14.           
  15.       
  16.     def run(self):       #重写threading.Thread中的run()  
  17.         while self.isrunning:  
  18.             print 'thread %s is running,time:%s\n' %(self.getName(),time.ctime()) #获得线程的名称和当前时间  
  19.             time.sleep(self.interval)  
  20.     def stop(self):  
  21.         self.isrunning = False  
  22.   
  23. def test():  
  24.     thread1 = race('A',1)  
  25.     thread2 = race('B',2)  
  26.     thread1.start()  
  27.     thread2.start()  
  28.     time.sleep(5)  
  29.     thread1.stop()  
  30.     thread2.stop()  
  31.       
  32. if __name__ =='__main__':  
  33.     test()  
 

3. 在threading.Thread中指定目标函数作为线程处理函数

Python代码   收藏代码
  1. # -*- coding: utf-8 -*-   
  2. from threading import Thread    
  3. def run_thread(n):    
  4.         for i in range(n):    
  5.             print i    
  6.     
  7. t1 = Thread(target=run_thread,args=(5,))#指定目标函数,传入参数,这里参数也是元组  
  8. t1.start()  #启动线程  

 

二. threading.Thread中常用函数说明

 

       函数名                                               功能
run()如果采用方法2创建线程就需要重写该方法
getName()获得线程的名称(方法2中有示例)
setName()设置线程的名称
start()启动线程
join(timeout) 在join()位置等待另一线程结束后再继续运行join()后的操作,timeout是可选项,表示最大等待时间
setDaemon(bool)True:当父线程结束时,子线程立即结束;False:父线程等待子线程结束后才结束。默认为False
isDaemon()判断子线程是否和父线程一起结束,即setDaemon()设置的值
isAlive() 判断线程是否在运行

 

以上方法中,我将对join()和setDaemon(bool)作着重介绍,示例如下:


(1)join方法:

Java代码   收藏代码
  1. # -*- coding: utf-8 -*-   
  2. import threading    
  3. import time     #导入time模块    
  4. class Mythread(threading.Thread):    
  5.     def __init__(self,threadname):    
  6.         threading.Thread.__init__(self,name = threadname)    
  7.     def run(self):    
  8.         time.sleep(2)   
  9.         for i in range(5):  
  10.             print '%s is running····'%self.getName()    
  11.      
  12. t2 = Mythread('B')    
  13. t2.start()  
  14. #t2.join()       
  15. for i in range(5):  
  16.     print 'the program is running···'  

 

这时的程序流程是:主线程先运行完,然后等待B线程运行,所以输出结果为:

 

Python代码   收藏代码
  1. the program is running···  
  2. the program is running···  
  3. the program is running···  
  4. is running····  
  5. is running····  
  6. is running····  
 

如果启用t2.join() ,这时程序的运行流程是:当主线程运行到 t2.join() 时,它将等待 t2 运行完,然后再继续运行t2.join() 后的操作,呵呵,你懂了吗,所以输出结果为:

 

Python代码   收藏代码
  1. is running····  
  2. is running····  
  3. is running····  
  4. the program is running···  
  5. the program is running···  
  6. the program is running···  

 

(2)setDaemon方法:

Python代码   收藏代码
  1. # -*- coding: utf-8 -*-   
  2. import threading  
  3. import time   
  4. class myThread(threading.Thread):  
  5.     def __init__(self, threadname):  
  6.         threading.Thread.__init__(self, name=threadname)  
  7.           
  8.     def run(self):  
  9.         time.sleep(5)  
  10.         print '%s is running·······done'%self.getName()  
  11.       
  12. t=myThread('son thread')  
  13. #t.setDaemon(True)  
  14. t.start()  
  15. if t.isDaemon():  
  16.     print "the father thread and the son thread are done"  
  17. else:  
  18.     print "the father thread is waiting the son thread····"  
 

这段代码的运行流程是:主线程打印完最后一句话后,等待son thread  运行完,然后程序才结束,所以输出结果为:

 

Python代码   收藏代码
  1. the father thread is waitting the son thread····  
  2. son thread is running·······done  

 

如果启用t.setDaemon(True) ,这段代码的运行流程是:当主线程打印完最后一句话后,不管 son thread 是否运行完,程序立即结束,所以输出结果为:

 

Python代码   收藏代码
  1. the father thread and the son thread are done  
 

三. 小结 
介绍到这里,python多线程使用级别的知识点已全部介绍完了,下面我会分析一下python多线程的同步问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值