python - 全局计数器线程在 python 中安全吗?

标签 python

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()

Python 版本为 2.7.5。

上面的代码,我跑了好几次,最后的结果都是3000。

而这段代码也是本博客的例子。 http://effbot.org/zone/thread-synchronization.htm

但是这个博客也提到了:

In general, this approach only works if the shared resource consists of a single instance of a core data type, such as a string variable, a number, or a list or dictionary. Here are some thread-safe operations:

  • reading or replacing a single instance attribute
  • reading or replacing a single global variable
  • fetching an item from a list
  • modifying a list in place (e.g. adding an item using append)
  • fetching an item from a dictionary
  • modifying a dictionary in place (e.g. adding an item, or calling the clear method)

这让我感到困惑,我们真的需要锁才能在 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

我是否遗漏了一些可能导致差异的东西?

更新 2

另一个观察结果是我上面使用的 linux box 只有一个内核。当我切换到另一个有 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        

这里的代码将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

这里线程 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

这是我在 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

关于python - 全局计数器线程在 python 中安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37990533/

相关文章:

Python 2.7 多处理日志记录和循环

python - 使用 asyncio_mongo 在 mongodb 上插入

python - 多维索引切片后数组的维度

python - 如何在每次迭代中访问列表中的 'window' 个元素?

python - 如何在 Ubuntu 中运行 Anaconda 提示符

python - 分割数据集以解决分类问题的正确程序是什么?

python - 为什么单独执行 softmax 和 crossentropy 与使用 softmax_cross_entropy_with_logits 一起执行它们会产生不同的结果?

python - 在ctypes中读取c函数返回的数组

python - 库未加载 : @rpath/libopenblasp-r0. 2.19.dylib

python - 如何在 Python 中获取原始命令行?带空格、制表符等