python 多线程编程

来源:互联网 发布:姚振华 知乎 编辑:程序博客网 时间:2024/04/19 04:40

一)线程基础

1、创建线程:

thread模块提供了start_new_thread函数,用以创建线程。start_new_thread函数成功创建后还可以对其进行操作。

其函数原型:

    start_new_thread(function,atgs[,kwargs])

其参数含义如下:

    function: 在线程中执行的函数名

    args:元组形式的参数列表。

    kwargs: 可选参数,以字典的形式指定参数

方法一:通过使用thread模块中的函数创建新线程。

[python] view plaincopy
  1. >>> import thread  
  2. >>> def run(n):  
  3.     for i in range(n):  
  4.         print i  
  5.   
  6.           
  7. >>> thread.start_new_thread(run,(4,))   #注意第二个参数一定要是元组的形式  
  8. 53840  
  9.   
  10.   
  11. 1  
  12. >>>   
  13. 2  
  14. 3  
  15. KeyboardInterrupt  
  16. >>> thread.start_new_thread(run,(2,))  
  17. 17840  
  18.   
  19.   
  20. 1  
  21. >>>   
  22. thread.start_new_thread(run,(),{'n':4})  
  23. 39720  
  24.   
  25.   
  26. 1  
  27. >>>   
  28. 2  
  29. 3  
  30. thread.start_new_thread(run,(),{'n':3})  
  31. 32480  
  32.   
  33.   
  34. 1  
  35. >>>   
  36. 2  

方法二:通过继承threading.Thread创建线程

[python] view plaincopy
  1. >>> import threading  
  2. >>> class mythread(threading.Thread):  
  3.     def __init__(self,num):  
  4.         threading.Thread.__init__(self)  
  5.         self.num = num  
  6.     def run(self):               #重载run方法  
  7.         print 'I am'self.num  
  8.   
  9.           
  10. >>> t1 = mythread(1)  
  11. >>> t2 = mythread(2)  
  12. >>> t3 = mythread(3)  
  13. >>> t1.start()           #运行线程t1  
  14. I am  
  15. >>>  1  
  16. t2.start()  
  17. I am  
  18. >>>  2  
  19. t3.start()  
  20. I am  
  21. >>>  3  

方法三:使用threading.Thread直接在线程中运行函数。

[python] view plaincopy
  1. import threading  
  2. >>> def run(x,y):  
  3.     for i in range(x,y):  
  4.         print i  
  5.   
  6. >>> t1 = threading.Thread(target=run,args=(15,20)) #直接使用Thread附加函数args为函数参数  
  7.   
  8. >>> t1.start()  
  9. 15  
  10. >>>   
  11. 16  
  12. 17  
  13. 18  
  14. 19  

 

二)Thread对象中的常用方法:

1、isAlive方法:

[python] view plaincopy
  1. >>> import threading  
  2. >>> import time  
  3. >>> class mythread(threading.Thread):  
  4.     def __init__(self,id):  
  5.         threading.Thread.__init__(self)  
  6.         self.id = id  
  7.     def run(self):  
  8.         time.sleep(5)    #休眠5秒  
  9.         print self.id  
  10.   
  11.           
  12. >>> t = mythread(1)  
  13. >>> def func():  
  14.     t.start()  
  15.     print t.isAlive()    #打印线程状态  
  16.   
  17.       
  18. >>> func()  
  19. True  
  20. >>> 1  

2、join方法:

原型:join([timeout]) 

    timeout: 可选参数,线程运行的最长时间

[python] view plaincopy
  1. import threading  
  2. >>> import time     #导入time模块  
  3. >>> class Mythread(threading.Thread):  
  4.     def __init__(self,id):  
  5.         threading.Thread.__init__(self)  
  6.         self.id = id  
  7.     def run(self):  
  8.         x = 0  
  9.         time.sleep(20)  
  10.         print self.id  
  11.   
  12.           
  13. >>> def func():  
  14.     t.start()  
  15.     for i in range(5):  
  16.         print i  
  17.   
  18.           
  19. >>> t = Mythread(2)  
  20. >>> func()  
  21. 0  
  22. 1  
  23. 2  
  24. 3  
  25. 4  
  26. >>> 2  
  27. def func():  
  28.     t.start()  
  29.     t.join()  
  30.     for i in range(5):  
  31.         print i  
  32.   
  33.           
  34. >>> t = Mythread(3)  
  35. >>> func()  
  36. 3  
  37. 0  
  38. 1  
  39. 2  
  40. 3  
  41. 4  
  42. >>>   

 

3、线程名:

[python] view plaincopy
  1. >>> import threading  
  2. >>> class mythread(threading.Thread):  
  3.     def __init__(self,threadname):  
  4.         threading.Thread.__init__(self,name=threadname)  
  5.     def run(self):  
  6.         print self.getName()  
  7.   
  8.           
  9. >>>   
  10. >>> t1 = mythread('t1')  
  11. >>> t1.start()  
  12. t1  
  13. >>>   

 4、setDaemon方法

在脚本运行的过程中有一个主线程,如果主线程又创建了一个子线程,那么当主线程退出时,会检验子线程是否完成。如果子线程未完成,则主线程会在等待子线程完成后退出。

当需要主线程退出时,不管子线程是否完成都随主线程退出,则可以使用Thread对象的setDaemon方法来设置。

 

三)线程同步

1.简单的线程同步

使用Thread对象的Lock和RLock可以实现简单的线程同步。对于如果需要每次只有一个线程操作的数据,可以将操作过程放在acquire方法和release方法之间。如:

 

[python] view plaincopy
  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.     def run(self):  
  8.         global x                #设置全局变量  
  9. #       lock.acquire()          #调用lock的acquire方法  
  10.         for i in range(3):  
  11.             x = x + 1  
  12.         time.sleep(2)  
  13.         print x  
  14. #       lock.release()          #调用lock的release方法  
  15. #lock = threading.RLock()        #生成Rlock对象  
  16. t1 = []  
  17. for i in range(10):  
  18.     t = mythread(str(i))  
  19.     t1.append(t)  
  20. x = 0                   #将全局变量的值设为0  
  21. for i in t1:   
  22.     i.start()  
  23.   
  24. E:/study/python/workspace>xianchengtongbu.py  
  25. 3  
  26. 6  
  27. 9  
  28. 12  
  29. 15  
  30. 18  
  31. 21  
  32. 24  
  33. 27  
  34. 30  

如果将lock.acquire()和lock.release(),lock = threading.Lock()删除后保存运行脚本,结果将是输出10个30。30是x的最终值,由于x是全局变量,每个线程对其操作后进入休眠状态,在线程休眠的时候,python解释器就执行了其他的线程而是x的值增加。当所有线程休眠结束后,x的值已被所有线修改为了30,因此输出全部为30。

 

2、使用条件变量保持线程同步。

Python的Condition对象提供了对复制线程同步的支持。使用Condition对象可以在某些事件触发后才处理数据。Condition对象除了具有acquire方法和release的方法外,还有wait方法、notify方法、notifyAll方法等用于条件处理。

[python] view plaincopy
  1. # -*- coding:utf-8 -*-  
  2. import threading  
  3. class Producer(threading.Thread):  
  4.     def __init__(self,threadname):  
  5.         threading.Thread.__init__(self,name = threadname)  
  6.     def run(self):  
  7.         global x  
  8.         con.acquire()  
  9.         if x == 1000000:  
  10.             con.wait()  
  11.         #   pass  
  12.         else:  
  13.             for i in range(1000000):  
  14.                 x = x + 1  
  15.             con.notify()  
  16.         print x  
  17.         con.release()  
  18. class Consumer(threading.Thread):  
  19.     def __init__(self,threadname):  
  20.         threading.Thread.__init__(self,name = threadname)  
  21.     def run(self):  
  22.         global x   
  23.         con.acquire()  
  24.         if x == 0:  
  25.             con.wait()  
  26.             #pass  
  27.         else:  
  28.             for i in range(1000000):  
  29.                 x = x - 1  
  30.             con.notify()  
  31.         print x   
  32.         con.release()  
  33. con = threading.Condition()  
  34. x = 0  
  35. p = Producer('Producer')  
  36. c = Consumer('Consumer')  
  37. p.start()  
  38. c.start()  
  39. p.join()  
  40. c.join()  
  41. print x  
  42.   
  43. E:/study/python/workspace>xianchengtongbu2.py  
  44. 1000000  
  45. 0  
  46. 0  

线程间通信:

Event对象用于线程间的相互通信。他提供了设置信号、清除信宏、等待等用于实现线程间的通信。

1、设置信号。Event对象使用了set()方法后,isSet()方法返回真。

2、清除信号。使用Event对象的clear()方法后,isSet()方法返回为假。

3、等待。当Event对象的内部信号标志为假时,则wait()方法一直等到其为真时才返回。还可以向wait传递参数,设定最长的等待时间。

[python] view plaincopy
  1. # -*- coding:utf-8 -*-  
  2. import threading  
  3. class mythread(threading.Thread):  
  4.     def __init__(self,threadname):  
  5.         threading.Thread.__init__(self,name = threadname)  
  6.     def run(self):  
  7.         global event  
  8.         if event.isSet():  
  9.             event.clear()  
  10.             event.wait()   #当event被标记时才返回  
  11.             print self.getName()  
  12.         else:  
  13.             print self.getName()  
  14.             event.set()  
  15. event = threading.Event()  
  16. event.set()  
  17. t1 = []  
  18. for i in range(10):  
  19.     t = mythread(str(i))  
  20.     t1.append(t)  
  21. for i in t1:  
  22.     i.start()