Python多线程基础

来源:互联网 发布:js计算时间差天数 编辑:程序博客网 时间:2024/05/19 21:00

http://www.17jo.com/program/python/app/ThreadUse.html

1. Python多线程基础


       Python多线程编程,当程序需要同时并发处理多个任务时,就需要要使用多线程编程。

继承线程类threading.thread,再重载成员函数run,程序处理的代码写在函数run中,最后再调用start()方法来运行线程,而join()方法可以用来等待线程结束。

    多线程的资源同步,可使用thread.RLock()来创建资源锁,然后使用acquire()来锁住资源,release()来释放资源。等待事件用thread.Event(),用wait()来等待事件,set()来激发事件,clear()用于清除已激发事件。

另外可以用isAlive()来判断线程是否存活着。

例:多线程编程

[cpp] view plaincopy
  1. #!/usr/bin/env python  
  2. #threads1.py  
  3. import time                 # 导入时间模块  
  4. import threading as thread  # 导入线程模块  
  5. class Thread1(thread.Thread):  
  6.     def __init__(self):  
  7.         thread.Thread.__init__(self)    # 默认初始化  
  8.         self.lock = thread.RLock()      # 创建资源锁  
  9.         self.flag = True  
  10.         self.count = 0  
  11.     def run(self):  
  12.         print 'Thread1 run'  
  13.         while self.count < 3:  
  14.             self.lock.acquire()         # 锁住资源  
  15.             self.count += 1  
  16.             print self.count            # 输出计数  
  17.             self.lock.release()         # 释放资源  
  18.             time.sleep(1)               # 线程休眠1秒  
  19.         print 'Thread1 end'  
  20.           
  21. class Thread2(thread.Thread):  
  22.     def __init__(self,event):  
  23.         thread.Thread.__init__(self)    # 初始化线程  
  24.         self.event = event  
  25.     def run(self):  
  26.         self.event.wait()               # 线程启动后等待事件  
  27.         print 'Thread2 run'  
  28.         self.event.clear()              # 清除事件  
  29.         print 'Thread2 end'  
  30. print 'program start'  
  31. event = thread.Event()  
  32. t1 = Thread1()  
  33. t2 = Thread2(event)  
  34. t1.start()              # 线程t1启动  
  35. t2.start()              # 线程t2启动  
  36. t1.join()               # 等待线程t1结束  
  37. event.set()             # 激发事件t2开始运行   
  38. t2.join()               # 等待线程t2结束  
  39. print 'program end'     # 结束程序  
  40. >> program start   # 输出  
  41. >> Thread1 run  
  42. >> 1  
  43. >> 2  
  44. >> 3  
  45. >> Thread1 end  
  46. >> Thread2 run  
  47. >> Thread2 end  
  48. >> program end  



2. Python多线程编程的两种方式


http://guanjh.iteye.com/blog/88904


Python中如果要使用线程的话,pythonlib中提供了两种方式。一种是函数式,一种是用类来包装的线程对象。举两个简单的例子希望起到抛砖引玉的作用,关于多线程编程的其他知识例如互斥、信号量、临界区等请参考python的文档及相关资料。


1.调用thread模块中的start_new_thread()函数来产生新的线程


请看代码:

[cpp] view plaincopy
  1. #!/usr/bin/env python  
  2. #thread_example1.py  
  3. import time  
  4. import _thread  
  5. def timer(no,interval):  
  6.     print('timer Begin:')  
  7.     while True:  
  8.         print('Thread :(%d) Time:%s'%(no,time.ctime()))  
  9.         time.sleep(interval)  
  10.           
  11. def test():  
  12.     print('Test Begin:')  
  13.     _thread.start_new_thread(timer,(1,1))  
  14.     _thread.start_new_thread(timer,(2,3))  
  15.   
  16. print(__name__)  
  17. if __name__=='__main__':  
  18.     test()  
  19.     time.sleep(20)  # 注意这里, 必须这样子, 因为如果不睡眠  
  20.                     # test()之后程序就直接退出了, 线程都没有来得及运行  


这个是thread.start_new_thread(function,args[,kwargs])函数原型,其中function参数是你将要调用的线程函数;args是讲传递给你的线程函数的参数,他必须是个tuple类型;而kwargs是可选的参数。

线程的结束一般依靠线程函数的自然结束;也可以在线程函数中调用thread.exit(),他抛出SystemExit exception,达到退出线程的目的。


2. 通过调用threading模块继承threading.Thread类来包装一个线程对象。


请看代码:

[cpp] view plaincopy
  1. #!/usr/bin/env python  
  2. #thread_example2.py  
  3. import threading  
  4. import time  
  5. class timer(threading.Thread):      #我的timer类继承自threading.Thread类     
  6.     def __init__(self,no,interval):      
  7.         #在我重写__init__方法的时候要记得调用基类的__init__方法     
  8.         threading.Thread.__init__(self)          
  9.         self.no=no     
  10.         self.interval=interval     
  11.    
  12.     def run(self):  #重写run()方法,把自己的线程函数的代码放到这里  
  13.         i = 4  
  14.         while i > 0:  
  15.             print(i)  
  16.             print('Thread Object (%d), Time:%s'%(self.no,time.ctime()))  
  17.             time.sleep(self.interval)  
  18.             i = i - 1  
  19.   
  20. def test():     
  21.     threadone=timer(1,1)    #产生2个线程对象     
  22.     threadtwo=timer(2,3)     
  23.     threadone.start()   #通过调用线程对象的.start()方法来激活线程     
  24.     threadtwo.start()     
  25.          
  26. if __name__=='__main__':     
  27.     test()    

其实threadthreading的模块中还包含了其他的很多关于多线程编程的东西,例如锁、定时器、获得激活线程列表等等,请大家仔细参考python的文档!


3. 我自己的习惯


我在使用C++时的多线程我更喜欢用线程函数的结束来代表线程的结束这样对于某些资源的释放情况更容易掌握一些

原创粉丝点击