编程的乐趣在于让程序越来越快,这里将给大家介绍一个种加快程序运行的的编程方式——多线程

 

1 著名的全局解释锁(GIL)

说起python并发编程,就不得不说著名的全局解释锁(GIL)了。有兴趣的同学可以我查找一下相关的资料了解一下GIL,在这里大家只要知道一点,因为GIL的存在, 对于任何Python程序,不管有多少的处理器,任何时候都总是只有一个线程在执行。
下面先看一个例子:
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Mon Jun 5 16:12:14 2017
  5.  
  6. @author: 80002419
  7. """
  8. import threading
  9. import time
  10.  
  11. def cost(fun):##定义一个装饰器,用来计算函数运行的时间
  12. def wrapper(*args,**kargs):
  13. before_tm = time.time()
  14. fun(*args,**kargs);
  15. after_tm = time.time()
  16. fun.__doc__
  17. print("{0} cost:{1}".format(fun.__name__,after_tm-before_tm))
  18. return wrapper
  19.  
  20. def fibs1(n):
  21. if (n == 1):
  22. return 0
  23. elif(n == 2):
  24. return 1
  25. else:
  26. return fibs1(n-2)+fibs1(n-1)
  27.  
  28. def fibs2(n):
  29. list = []
  30. if (n == 1):
  31. list = [0]
  32. return list[-1]
  33. elif(n == 2):
  34. list = [0,1]
  35. return list[-1]
  36. else:
  37. list = [0,1]
  38. for i in range(2,n):
  39. list.append(list[i-1]+list[i-2])
  40. return list[-1]
  41.  
  42. @cost
  43. def nothread():
  44. fibs1(35)
  45. fibs1(35)
  46.  
  47.  
  48. #@cost
  49. #def nothread1():
  50. # print(fibs2(40))
  51. # print(fibs2(40))
  52.  
  53. @cost
  54. #使用多线程的程序
  55. def inthread():
  56. threads = []
  57. for i in range(2):
  58. t = threading.Thread(target = fibs1,args =(35,))
  59. t.start()
  60. threads.append(t)
  61. for t in threads:
  62. t.join()
  63.  
  64. @cost
  65. def inthread1():
  66. for i in range(2):
  67. t = threading.Thread(target=fibs1, args=(35,))
  68. t.start()
  69. main_thread = threading.currentThread()
  70. for t in threading.enumerate():
  71. if t is main_thread:
  72. continue
  73. t.join()
  74.  
  75. nothread()
  76. inthread()

打印结果:

nothread cost:5.41788887978
inthread cost:14.6728241444
 
上面的例子对比了一个cpu密集型程序分别使用多线程和不使用多线程的情况,我们可以得到结论:
对于cpu密集型任务,使用多线程反而会减慢程序的运行。
这是为什么呢?
 因为GIL在任何时候,仅仅允许一个单一的线程能够获取Python对象或者C API。每100个字节的Python指令解释器将重新获取锁,这(潜在的)阻塞了I/O操作
同时 
GIL是必须的,这是Python设计的问题:Python解释器是非线程安全的。这意味着当从线程内尝试安全的访问Python对象的时候将有一个全局的强制锁。当然python

多线程也有可以加快程序运行的时候:当我们开发和网络通信或者数据输入/输出相关的程序,比如网络爬虫、文本处理等等。这时候由于网络情况和I/O的性能的限制,Python解释器会等待读写数据的函数调用返回,这个时候就可以利用多线程库提高并发效率了。这类任务我们称为IO(密集型任务)

 

2  Semaphore类 ——python对象访问量的控制

在多线程编程中,为了防止不同的线程同时对一个公用的资源(比如全部变量)进行修改,需要进行同时访问的数量(通常是1)。信号量同步基于内部计数器,每调用一次acquire(),计数器减1;每调用一次release(),计数器加1.当计数器为0时,acquire()调用被阻塞。
下面来看一个例子:
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Mon Jun 5 16:12:14 2017
  5.  
  6. @author: 80002419
  7. """
  8. from threading import Thread, Semaphore
  9. import time,threading
  10.  
  11. sema = Semaphore(3) # 定义一个信号量为3的Semaphone对象,
  12.  
  13. #定义一个测试函数作为,被访问的对象
  14. def test(tid):
  15. with sema:
  16. print("信号量:{0}".format(tid))
  17. time.sleep(0.5)
  18. print('release!')
  19.  
  20. thds = []
  21. for i in range(6):
  22. t = Thread(target = test,args=(i,))
  23. t.start()
  24. thds.append(t)
  25.  
  26. for t in thds:
  27. t.join()

打印结果:

信号量:2
信号量:1

信号量:0

release!

信号量:0

release!

信号量:0

release!

信号量:0

release!

release!

release!
 
结果分析 :
当信号量sema信号为0时,此时不再不允许进程对test 再进行访问了,release 之后才能再继续生成亲的进程对其访问,
Semaphore类的作用就是限制公共资源的访问量
 
3 锁——lock 与 Rlock
先看一段代码:
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Mon Jun 5 16:12:14 2017
  5.  
  6. @author: 80002419
  7. """
  8. from threading import Thread, Lock
  9. import time,threading
  10.  
  11. value = 0;
  12.  
  13. def changeValue():
  14. global value
  15. new = value + 1
  16. time.sleep(0.001)#让其它进程可以切换进来
  17. value = new
  18.  
  19. thds = []
  20. for _ in range(100):
  21. t = Thread(target = changeValue)
  22. t.start()
  23. thds.append(t)
  24.  
  25. for t in thds:
  26. t.join()
  27.  
  28. print(value)

打印结果:

18
结果分析: 多个线程同时访问 value 变量,经过cpu存储后,再写回内存,如果进程A,进程B,在访问value时 值为0 ,进程A经过函数处理后,value = 1 ,再写回内存,value =1 ,进程B 执行完成后,会刷新value 但是写回的value 还是1, 所以并不能保护执行了100次changeValue后,结果为100
 
那么我们怎么能保证执行的结果就是100呢:再看一段代码:
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Mon Jun 5 16:12:14 2017
  5.  
  6. @author: 80002419
  7. """
  8. from threading import Thread, Lock
  9. import time,threading
  10.  
  11. value = 0
  12.  
  13. lock = Lock()
  14.  
  15. def changeValue():
  16. global value
  17. with lock:
  18. new = value + 1
  19. time.sleep(0.001)#让其它进程可以切换进来
  20. value = new
  21.  
  22. thds = []
  23.  
  24. for _ in range(100):
  25. t = Thread(target = changeValue)
  26. t.start()
  27. thds.append(t)
  28. for t in thds:
  29. t.join()
  30. print(value)

打印结果:

100
Lock也可以叫做互斥锁,其实相当于信号量为1,上面例子lock 也就可以用 sema = Semaphore()代替
 
本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理

想要获取更多Python学习资料可以加
QQ:2955637827私聊
或加Q群630390733
大家一起来学习讨论吧!
 

最新文章

  1. 客户端JavaScript-如何执行
  2. LeetCode Nested List Weight Sum
  3. Python-3 语法
  4. SQL常用语句(2)
  5. jsf简介
  6. javaSwing文本框组件
  7. 16Spring_AOP编程(AspectJ)_最终通知
  8. 安装 PLSQL笔记
  9. Google桌面搜索引擎
  10. Mybatis高级映射、动态SQL及获得自增主键
  11. 将samba加入到windows域《转载》
  12. java打包/命令行方式运行jar(命令行进行程序测试)
  13. 冒泡排序java
  14. discuz!迁移指南
  15. POJ 2155 Matrix(二维树状数组)
  16. ArrayBuffer和TypedArray,以及Blob的使用
  17. Sony索尼数码录音笔MSV格式转换为MP3格式【转】
  18. 解决maven在build时下载文件卡死问题
  19. egret获取本周,上周,今天,昨天,明天,现在时间,今年,本月
  20. servlet运行“/*”引起的java.lang.StackOverflowError

热门文章

  1. git学习与应用
  2. NOIP2020 游记
  3. 【Makefile】5-Makefile变量的基础
  4. 学习关注:学习C++的前景
  5. Oracle11gR2 sqlplus中可以执行上键查询backspace删除
  6. java面试复习重点:类的管理及常用工具,教你抓住面试的重点!
  7. Calendar类、 System类、 StringBulider类、 包装类
  8. 肝了75天,五万五千字,《Spring Boot 进阶》专栏文章整理成册,分享~
  9. 网络编程原理与UDP实现
  10. Hbase 简单封装(Hbase 2.0+ API)