python多线程学习笔记(超详细)

时间:2021-12-29 02:28:35
python
threading
多线程

一. Threading简介

首先看下面的没有用Threading的程序


  1. ): 

  2. s += i 

  3. time.sleep( 



  4. ): 

  5. s += i 

  6. time.sleep()] 



  7. ): 

  8. print() 

  9. ): 

  10. print( 

  11. threading:  

  12. threading:  

  13. 主线程等待t这个线程 

  14. threading:  

  15. Main:  

  16. threading:  

  17. Main:  

  18. threading:  

  19. Main:  

  20. threading:  

  21. Main:  

  22. threading:  

  23. Main:  

  24. threading:  

  25. Main:  

  26. threading:  

  27. Main:  

  28. Main:  

  29. Main:  

  30. [Finished ) 

  31. print() 

  32. print(  

  33. lock = threading.Lock() ): 

  34. lock.acquire() 

  35. print(share) 

  36. share += self.i 

  37. time.sleep(random.random()) 

  38. print() 

  39. tt = MyThread() 

  40. t.start() 

  41. tt.start() 


  42. >>> 


  43. + =  


  44. + =  


  45. + =  


  46. + =  

  47. [Finished ):  



  48. + =  


  49. + =  


  50. + =  

  51. + =  

  52. [Finished  


  53. share_cond = threading.Condition() 



  54. print(self.name,share) 

  55. share_cond.notify() ) 






  56. Custom  

  57. Produce  

  58. Custom  

  59. Produce  

  60. Custom  

  61. ... 

  62. ... 

  63. ... 

上面的结果会一直重复执行下去

3 ) 信号量threading.Semaphore

属性

  • 实例化时,指定使用量。

  • 其内置计数器,锁定时+1,
    释放时-1,计数器为0则阻塞。

  • acquire(blocking=True,timeout=None)

  • release()释放锁。






  1. sema.release() 

  2. print(self.name,)] 

  3. Sema Had got resource. 

  4. Sema Had got resource. 

  5. Sema Had got resource. 

  6. Sema Had released resource. 

  7. Sema Had got resource. 

  8. Sema Had released resource. 

  9. Sema Had released resource. 

  10. Sema Had got resource. 

  11. Sema Had released resource. 

  12. Sema Had released resource. 

  13. [Finished ) 

  14. print('Main thread set event flag!') 

  15. event.set() 


  16. if __name__ == '__main__': 

  17. thw = MyThreadWait() 

  18. thm = MyThreadMain() 

  19. thw.start() 

  20. thm.start() 


  21. >>> 

  22. Wait Thread Wait... 

  23. Main thread set event flag! 

  24. Wait Thread Start... 

  25. [Finished in 3.6s] 

好了,大概就是这些了,其他的以后再补充,另外感谢麦子学院提供的免费课程~~~真心不是打广告python多线程学习笔记(超详细)
为了避嫌,顺便感谢一下imooc,极客学院~很多都是从这些造福人类的网站学到的。
另附上麦子学院的视频教程,毕竟要学会感恩嘛
http://www.maiziedu.com/course/644-9663/

marsggbo笔记出品,必属精品python多线程学习笔记(超详细)