原文地址:http://agiliq.com/blog/2013/09/understanding-threads-in-python/ , http://my.oschina.net/leejun2005/blog/179265
----------------
目录[-]
我们将会看到一些在 Python 中使用线程的实例和如何避免线程之间的竞争。
你应当将下边的例子运行多次,以便可以注意到线程是不可预测的和线程每次运行出的不同结果。声明:从这里开始忘掉你听到过的关于 GIL 的东西,因为 GIL 不会影响到我想要展示的东西。
示例1,我们将要请求五个不同的url:
1、单线程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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
Elapsed time: 3.0814409256
解释:
url顺序的被请求
除非cpu从一个url获得了回应,否则不会去请求下一个url
网络请求会花费较长的时间,所以cpu在等待网络请求的返回时间内一直处于闲置状态。
2、多线程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
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会首先被请求,然后打印出返回的结果。
示例2,全局变量的线程安全问题(race condition)
1、BUG 版
我们将会用一个程序演示一下多线程间的资源竞争,并修复这个问题。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
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的情况。
2、解决资源竞争
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
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成了逻辑上的原子操作。
示例3,多线程环境下的原子操作
让我们用一个例子来证明一个线程不能影响其他线程内的变量(非全局变量)。
time.sleep()可以使一个线程挂起,强制线程切换发生。
1、BUG 版
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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是个逻辑上的原子操作,以防打印时被其他线程打断。
2、加锁保证操作的原子性
我们使用了Lock(),来看下边的例子。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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()
|
这次我们看到了正确的结果。证明了一个线程不可以修改其他线程内部的变量(非全局变量)。
示例4,Python多线程简易版:线程池 threadpool
上面的多线程代码看起来有点繁琐,下面我们用 treadpool 将案例 1 改写下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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线程池
5、REF:
http://agiliq.com/blog/2013/09/understanding-threads-in-python/
http://www.zhidaow.com/post/python-threadpool
6、推荐阅读:
1、线程安全及Python中的GIL
http://www.cnblogs.com/mindsbook/archive/2009/10/15/thread-safety-and-GIL.html
2、Python 不能利用多核的问题以后能被解决吗?
本文主要讨论了 python 中的 单线程、多线程、多进程、异步、协程、多核、VM、GIL、GC、greenlet、Gevent、性能、IO 密集型、CPU 密集型、业务场景 等问题,以这些方面来判断去除 GIL 实现多线程的优劣:
http://www.zhihu.com/question/21219976
注:协程可以认为是一种用户态的线程,与系统提供的线程不同点是,它需要主动让出CPU时间,而不是由系统进行调度,即控制权在程序员手上,用来执行协作式多任务非常合适。
3、GIL 与线程调度
——《Python源码剖析--深度探索动态语言核心技术》第15章
大约在99年的时候,Greg Stein 和Mark Hammond 两位老兄基于Python 1.5 创建了一份去除GIL 的branch,但是很不幸,这个分支在很多基准测试上,尤其是单线程操作的测试上,效率只有使用GIL 的Python 的一半左右。
http://book.51cto.com/art/200807/82530.htm
4、Python中的生产者消费者问题
http://blog.jobbole.com/52412/
5、python 3.2 新特性:concurrent.futures — Launching parallel tasks
http://docs.python.org/dev/library/concurrent.futures.html#threadpoolexecutor-example
6、Python Multithreaded Programming
http://www.tutorialspoint.com/python/python_multithreading.htm
7、使用 Python 进行线程编程
http://www.ibm.com/developerworks/cn/aix/library/au-threadingpython/
8、Python模块学习 —- threading 多线程控制和处理
http://python.jobbole.com/81546/
9、Python的GIL是什么鬼,多线程性能究竟如何