咱们将会看到一些在 Python 中使用线程的实例和如何避免线程之间的竞争。
你应当将下边的例子运行屡次,以即可以注意到线程是不可预测的和线程每次运行出的不一样结果。声明:从这里开始忘掉你听到过的关于 GIL 的东西,由于 GIL 不会影响到我想要展现的东西。
html
import time import urllib2 def get_responses(): urls = [ 'http://www.google.com', 'http://www.amazon.com', 'http://www.ebay.com', 'http://www.alibaba.com', 'http://www.reddit.com' ] start = time.time() for url in urls: print url resp = urllib2.urlopen(url) print resp.getcode() print "Elapsed time: %s" % (time.time()-start) get_responses()
输出是:
http://www.google.com 200
http://www.amazon.com 200
http://www.ebay.com 200
http://www.alibaba.com 200
http://www.reddit.com 200
python
Elapsed time: 3.0814409256 git
解释: 程序员
url顺序的被请求
除非cpu从一个url得到了回应,不然不会去请求下一个url
网络请求会花费较长的时间,因此cpu在等待网络请求的返回时间内一直处于闲置状态。
github
import urllib2 import time from threading import Thread class GetUrlThread(Thread): def __init__(self, url): self.url = url super(GetUrlThread, self).__init__() def run(self): resp = urllib2.urlopen(self.url) print self.url, resp.getcode() def get_responses(): urls = [ 'http://www.google.com', 'http://www.amazon.com', 'http://www.ebay.com', 'http://www.alibaba.com', 'http://www.reddit.com' ] start = time.time() threads = [] for url in urls: t = GetUrlThread(url) threads.append(t) t.start() for t in threads: t.join() print "Elapsed time: %s" % (time.time()-start) get_responses()
输出:
http://www.reddit.com 200
http://www.google.com 200
http://www.amazon.com 200
http://www.alibaba.com 200
http://www.ebay.com 200
编程
Elapsed time: 0.689890861511 安全
解释:
意识到了程序在执行时间上的提高
咱们写了一个多线程程序来减小cpu的等待时间,当咱们在等待一个线程内的网络请求返回时,这时cpu能够切换到其余线程去进行其余线程内的网络请求。
咱们指望一个线程处理一个url,因此实例化线程类的时候咱们传了一个url。
线程运行意味着执行类里的run()方法。
不管如何咱们想每一个线程必须执行run()。
为每一个url建立一个线程而且调用start()方法,这告诉了cpu能够执行线程中的run()方法了。
咱们但愿全部的线程执行完毕的时候再计算花费的时间,因此调用了join()方法。
join()能够通知主线程等待这个线程结束后,才能够执行下一条指令。
每一个线程咱们都调用了join()方法,因此咱们是在全部线程执行完毕后计算的运行时间。
关于线程:
cpu可能不会在调用start()后立刻执行run()方法。
你不能肯定run()在不一样线程建间的执行顺序。
对于单独的一个线程,能够保证run()方法里的语句是按照顺序执行的。
这就是由于线程内的url会首先被请求,而后打印出返回的结果。
网络
咱们将会用一个程序演示一下多线程间的资源竞争,并修复这个问题。 多线程
from threading import Thread #define a global variable some_var = 0 class IncrementThread(Thread): def run(self): #we want to read a global variable #and then increment it global some_var read_value = some_var print "some_var in %s is %d" % (self.name, read_value) some_var = read_value + 1 print "some_var in %s after increment is %d" % (self.name, some_var) def use_increment_thread(): threads = [] for i in range(50): t = IncrementThread() threads.append(t) t.start() for t in threads: t.join() print "After 50 modifications, some_var should have become 50" print "After 50 modifications, some_var is %d" % (some_var,) use_increment_thread()
屡次运行这个程序,你会看到多种不一样的结果。
解释:
有一个全局变量,全部的线程都想修改它。
全部的线程应该在这个全局变量上加 1 。
有50个线程,最后这个数值应该变成50,可是它却没有。
为何没有达到50?
在some_var是15的时候,线程t1读取了some_var,这个时刻cpu将控制权给了另外一个线程t2。
t2线程读到的some_var也是15
t1和t2都把some_var加到16
当时咱们指望的是t1 t2两个线程使some_var + 2变成17
在这里就有了资源竞争。
相同的状况也可能发生在其它的线程间,因此出现了最后的结果小于50的状况。 app
from threading import Lock, Thread lock = Lock() some_var = 0 class IncrementThread(Thread): def run(self): #we want to read a global variable #and then increment it global some_var lock.acquire() read_value = some_var print "some_var in %s is %d" % (self.name, read_value) some_var = read_value + 1 print "some_var in %s after increment is %d" % (self.name, some_var) lock.release() def use_increment_thread(): threads = [] for i in range(50): t = IncrementThread() threads.append(t) t.start() for t in threads: t.join() print "After 50 modifications, some_var should have become 50" print "After 50 modifications, some_var is %d" % (some_var,) use_increment_thread()
再次运行这个程序,达到了咱们预期的结果。
解释:
Lock 用来防止竞争条件
若是在执行一些操做以前,线程t1得到了锁。其余的线程在t1释放Lock以前,不会执行相同的操做
咱们想要肯定的是一旦线程t1已经读取了some_var,直到t1完成了修改some_var,其余的线程才能够读取some_var
这样读取和修改some_var成了逻辑上的原子操做。
让咱们用一个例子来证实一个线程不能影响其余线程内的变量(非全局变量)。
time.sleep()可使一个线程挂起,强制线程切换发生。
from threading import Thread import time class CreateListThread(Thread): def run(self): self.entries = [] for i in range(10): time.sleep(0.01) self.entries.append(i) print self.entries def use_create_list_thread(): for i in range(3): t = CreateListThread() t.start() use_create_list_thread()
运行几回后发现并无打印出正确的结果。当一个线程正在打印的时候,cpu切换到了另外一个线程,因此产生了不正确的结果。咱们须要确保print self.entries是个逻辑上的原子操做,以防打印时被其余线程打断。
咱们使用了Lock(),来看下边的例子。
from threading import Thread, Lock import time lock = Lock() class CreateListThread(Thread): def run(self): self.entries = [] for i in range(10): time.sleep(0.01) self.entries.append(i) lock.acquire() print self.entries lock.release() def use_create_list_thread(): for i in range(3): t = CreateListThread() t.start() use_create_list_thread()
此次咱们看到了正确的结果。证实了一个线程不能够修改其余线程内部的变量(非全局变量)。
上面的多线程代码看起来有点繁琐,下面咱们用 treadpool 将案例 1 改写下:
import threadpool import time import urllib2 urls = [ 'http://www.google.com', 'http://www.amazon.com', 'http://www.ebay.com', 'http://www.alibaba.com', 'http://www.reddit.com' ] def myRequest(url): resp = urllib2.urlopen(url) print url, resp.getcode() def timeCost(request, n): print "Elapsed time: %s" % (time.time()-start) start = time.time() pool = threadpool.ThreadPool(5) reqs = threadpool.makeRequests(myRequest, urls, timeCost) [ pool.putRequest(req) for req in reqs ] pool.wait()
解释关键代码:
ThreadPool(poolsize)
表示最多能够建立poolsize这么多线程;
makeRequests(some_callable, list_of_args, callback)
makeRequests建立了要开启多线程的函数,以及函数相关参数和回调函数,其中回调函数能够不写,default是无,也就是说makeRequests只须要2个参数就能够运行;
注意:threadpool 是非线程安全的。
详情请参考:
http://blog.csdn.net/hzrandd/article/details/10074163 python 线程池的研究及实现
http://www.the5fire.com/python-thread-pool.html python线程池
http://agiliq.com/blog/2013/09/understanding-threads-in-python/
http://www.zhidaow.com/post/python-threadpool
http://www.cnblogs.com/mindsbook/archive/2009/10/15/thread-safety-and-GIL.html
本文主要讨论了 python 中的 单线程、多线程、多进程、异步、协程、多核、VM、GIL、GC、greenlet、Gevent、性能、IO 密集型、CPU 密集型、业务场景 等问题,以这些方面来判断去除 GIL 实现多线程的优劣:
http://www.zhihu.com/question/21219976
注:协程能够认为是一种用户态的线程,与系统提供的线程不一样点是,它须要主动让出CPU时间,而不是由系统进行调度,即控制权在程序员手上,用来执行协做式多任务很是合适。
——《Python源码剖析--深度探索动态语言核心技术》第15章
大约在99年的时候,Greg Stein 和Mark Hammond 两位老兄基于Python 1.5 建立了一份去除GIL 的branch,可是很不幸,这个分支在不少基准测试上,尤为是单线程操做的测试上,效率只有使用GIL 的Python 的一半左右。
http://book.51cto.com/art/200807/82530.htm
http://blog.jobbole.com/52412/
五、python 3.2 新特性:concurrent.futures — Launching parallel tasks
http://docs.python.org/dev/library/concurrent.futures.html#threadpoolexecutor-example
六、Python Multithreaded Programming
http://www.tutorialspoint.com/python/python_multithreading.htm
七、使用 Python 进行线程编程
http://www.ibm.com/developerworks/cn/aix/library/au-threadingpython/
八、Python模块学习 —- threading 多线程控制和处理
http://python.jobbole.com/81546/
九、Python的GIL是什么鬼,多线程性能究竟如何