gpt4 book ai didi

python - 具有局部变量的全局方法线程安全

转载 作者:行者123 更新时间:2023-12-01 08:07:06 26 4
gpt4 key购买 nike

我有一个 python 项目,我在其中添加一个包含以下内容的新文件 utils.py 。它将被不同的线程访问。

def get_return_string(input_string, input_dict):
ret_str = 'some default value'
if 'apple' in input_string:
ret_str = input_dict['apple']
elif 'banana' in input_string:
ret_str = input_dict['banana']
elif 'grapes' in input_string:
ret_str = input_dict['grapes']
elif 'spinach' in input_string:
ret_str = input_dict['spinach']
elif 'orange' in input_string:
ret_str = input_dict['orange']
elif 'berry' in input_string:
ret_str = input_dict['berry']
return ret_str

只有局部变量,它们是从另一个类的内部实例中调用的。这个方法线程安全吗?

我读到here那:

Local variables are certainly "thread-exclusive." No other thread can access them directly, and this is helpful but not sufficient to guarantee semantic thread safety. A local variable in one thread does not store its value in the same location as the same-named local variable in another thread

However, guaranteeing that two threads have separate storage for local variables is not enough to ensure thread-safety, because those local variables can refer to globally shared data in a thread-unsafe way.

如果该方法是类方法而不是全局方法,那么它的行为也会有所不同:

class Utils():

@classmethod
def get_return_string(cls, input_string, input_dict):
#...same as above...

最佳答案

是的,该函数是线程安全的,因为局部变量实际上没有访问任何全局变量,您可以通过在方法中打印 ret_str 的值来检查

def get_return_string(input_string, input_dict):
ret_str = 'some default value'
if 'apple' in input_string:
ret_str = input_dict['apple']
elif 'banana' in input_string:
ret_str = input_dict['banana']
elif 'grapes' in input_string:
ret_str = input_dict['grapes']
elif 'spinach' in input_string:
ret_str = input_dict['spinach']
elif 'orange' in input_string:
ret_str = input_dict['orange']
elif 'berry' in input_string:
ret_str = input_dict['berry']
print(ret_str)
return ret_str

from threading import Thread

dct = {'apple':1,'banana':2}
t1 = Thread(target=get_return_string, args=('apple',dct))
t2 = Thread(target=get_return_string, args=('fruit',dct))
t3 = Thread(target=get_return_string, args=('banana',dct))
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
#1
#some default value
#2

关于python - 具有局部变量的全局方法线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55488473/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com