在多线程程序中的字典上使用 .copy() 是否安全?
Is it safe to use .copy() on a dictionary in a multi-threaded program?
示例代码。我创建了一个全局字典,并有一个创建本地副本的测试函数。我将同时拥有多个线程 运行 test()。
dictionary = {'test': 2}
def test():
local_dict = dictionary.copy()
local_dict['test'] += 1
return local_dict
### multi-threaded logic calling test() function
我发现了我遇到的问题。我用的是嵌套字典,需要用deepcopy来防止不同线程错误修改数据的问题,像这样:
import copy
dictionary = {'test': {'test': 2}}
def test():
local_dict = copy.deepcopy(dictionary)
local_dict['test'] += 1
return local_dict
### multi-threaded logic calling test() function
示例代码。我创建了一个全局字典,并有一个创建本地副本的测试函数。我将同时拥有多个线程 运行 test()。
dictionary = {'test': 2}
def test():
local_dict = dictionary.copy()
local_dict['test'] += 1
return local_dict
### multi-threaded logic calling test() function
我发现了我遇到的问题。我用的是嵌套字典,需要用deepcopy来防止不同线程错误修改数据的问题,像这样:
import copy
dictionary = {'test': {'test': 2}}
def test():
local_dict = copy.deepcopy(dictionary)
local_dict['test'] += 1
return local_dict
### multi-threaded logic calling test() function