import threading
import time
counter = 0
def increase(name):
global counter
i = 0
while i < 30:
# this for loop is for consuming cpu
for x in xrange(100000):
1+1
counter += 1
print name + " " + str(counter)
i += 1
if __name__ == '__main__':
threads = []
try:
for i in xrange(100):
name = "Thread-" + str(i)
t = threading.Thread( target=increase, args=(name,) )
t.start()
threads.append(t)
except:
print "Error: unable to start thread"
for t in threads:
t.join()
Run Code Online (Sandbox Code Playgroud)
Python版本是2.7.5.
对于上面的代码,我运行了几次,最终结果总是3000.
这段代码也是这个博客的例子. http://effbot.org/zone/thread-synchronization.htm
但是这篇博客还提到:
通常,此方法仅在共享资源由核心数据类型的单个实例(例如字符串变量,数字或列表或字典)组成时才有效.以下是一些线程安全的操作:
- 读取或替换单个实例属性
- 读取或替换单个全局变量
- 从列表中获取项目
- 修改列表(例如使用append添加项目)
- 从字典中获取项目
- 修改字典(例如添加项目或调用clear方法)
这让我感到困惑,我们真的需要锁定才能在python中使用多线程获得正确的结果吗?
更新1
我的Linux发行版是CentOS Linux release 7.2.1511内核版本3.10.0-123.el7.x86_64 #1 SMP Mon Jun 30 12:09:22 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux.
我的mac是版本10.11.5(15F34),python版本是2.7.10.
我在我的Mac上运行程序,结果是预期的,计数器不等于预期,因为使用了非线程安全的全局计数器.
但是当我在Linux上运行程序时,结果总是等于预期值.
counter:3000, expected:3000
counter:3000, expected:3000
counter:3000, expected:3000
counter:3000, expected:3000
counter:3000, expected:3000
Run Code Online (Sandbox Code Playgroud)
我在这里想念一些可能导致差异的东西吗?
更新2
另一个观察是我上面使用的linux盒子只有一个核心.当我切换到另一个有4个内核的Linux机箱时,结果是预期的.
根据我对Python GIL的理解,它保证程序将始终在单个核心上运行,无论平台有多少核心.但是GIL不能保证不同线程之间的安全吗?
如果这样,为什么单核机器会给出这样的结果呢?
谢谢.
即使在CPython中也不安全.虽然GIL保护单个操作码执行,但+=实际上扩展为几个指令:
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import dis
>>> counter = 0
>>> def inc():
... global counter
... counter += 1
...
>>> dis.dis(inc)
3 0 LOAD_GLOBAL 0 (counter)
3 LOAD_CONST 1 (1)
6 INPLACE_ADD
7 STORE_GLOBAL 0 (counter)
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
Run Code Online (Sandbox Code Playgroud)
这里的代码加载counter到堆栈上,递增并存储回来; 因此,LOAD_GLOBAL和STORE_GLOBAL之间存在竞争条件.让我们假设运行的两个线程inc被抢占如下:
Thread 1 Thread 2
LOAD_GLOBAL 0
LOAD_CONST 1
INPLACE_ADD
LOAD_GLOBAL 0
LOAD_CONST 1
INPLACE_ADD
STORE_GLOBAL 0
STORE_GLOBAL 0
LOAD_CONST 0
RETURN_VALUE
LOAD_CONST 0
RETURN_VALUE
Run Code Online (Sandbox Code Playgroud)
这里线程2完成的增量完全丢失,因为线程1 counter用他增加的陈旧值覆盖.
您可以轻松地验证这一点,从而消除代码中的大部分浪费,并让它们"比赛难":
import threading
import time
counter = 0
loops_per_increment = 10000
def increment(name):
global counter
i = 0
while i < loops_per_increment:
counter += 1
i += 1
if __name__ == '__main__':
expected = 0
threads = []
try:
for i in xrange(100):
name = "Thread-" + str(i)
t = threading.Thread( target=increment, args=(name,) )
expected += loops_per_increment
t.start()
threads.append(t)
except:
print "Error: unable to start thread"
for t in threads:
t.join()
print counter, "- expected:", expected
Run Code Online (Sandbox Code Playgroud)
这是我在8核机器上获得的一些数字:
[mitalia@mitalia ~/scratch]$ for i in (seq 10)
python inc.py
end
47012 - expected: 1000000
65696 - expected: 1000000
51456 - expected: 1000000
44628 - expected: 1000000
52087 - expected: 1000000
50812 - expected: 1000000
53277 - expected: 1000000
49652 - expected: 1000000
73703 - expected: 1000000
53902 - expected: 1000000
Run Code Online (Sandbox Code Playgroud)