线程安全的Python函数属性?

时间:2015-02-27 17:32:19

标签: python thread-safety

我在python函数属性的线程安全性上看到了2个不同的答案。假设一个进程可能有多个线程,并且认为函数是全局的,那么将函数属性用作静态存储是否存在明确的问题?请不要根据编程风格偏好给出答案。

1 个答案:

答案 0 :(得分:1)

你所描述的内容并没有真正错误。 A"静态"用于保存变量的全局函数对象:

from threading import Thread
def static():
    pass
static.x = 0
def thread():
    static.x += 1
    print(static.x)
for nothing in range(10):
    Thread(target=thread).start()

输出:

1
2
3
4
5
6
7
8
9
10

那"工作"因为每个线程都会在相同的时间内快速执行并完成。但是,让我们假设您的线程运行任意时间长度:

from threading import Thread
from time import sleep
from random import random

from threading import Thread
def static():
    pass
static.x = 0
def thread():
    static.x += 1
    x = static.x
    sleep(random())
    print(x)
for nothing in range(10):
    Thread(target=thread).start()

输出:

2
3
8
1
5
7
10
4
6
9

行为变得不明确。

<强>修订: 正如tdelaney指出的那样,

  

&#34; [第一个例子仅适用于运气并且会随机失败   反复跑......&#34;

第一个示例旨在说明多线程如何出现才能正常运行。它绝不是线程安全的代码。

修订II:您可能需要查看this question