我有一个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 method
而不是global method
,则其行为是否也会有所不同:
class Utils():
@classmethod
def get_return_string(cls, input_string, input_dict):
#...same as above...
是的,该函数是线程安全的,因为局部变量实际上没有访问任何全局变量,您可以通过在方法中打印ret\u str的值进行检查
相关问题 更多 >
编程相关推荐