局部变量的全局线程安全方法

2024-04-26 00:22:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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...

Tags: toininputstringreturnlocalnotvariables
1条回答
网友
1楼 · 发布于 2024-04-26 00:22:37

是的,该函数是线程安全的,因为局部变量实际上没有访问任何全局变量,您可以通过在方法中打印ret\u 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

相关问题 更多 >