Home > OS >  Is it safe to use .copy() on a dictionary in a multi-threaded program?
Is it safe to use .copy() on a dictionary in a multi-threaded program?

Time:10-13

Example code. I create a global dictionary, and have a test function which makes a local copy. I will have many threads running test() at once.

dictionary = {'test': 2}

def test():
   local_dict = dictionary.copy()
   local_dict['test']  = 1
   return local_dict

### multi-threaded logic calling test() function

CodePudding user response:

I figured out the issue I was having. I was used a nested dictionary, and needed to use deepcopy to prevent the issue where different threads were wrongly modifying data, like so:

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
  • Related