Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 dictionary being modified at another thread does not show changes after those modifications at the original thread [closed]

Python version: (3.9, but the same result with python 3.12)

The goal was that another thread modified a dictionary and those modifications to be available at the original thread.

import multiprocessing as mp
import sys

def my_func(result: dict):
    print(f'variable address at worker: {hex(id(result))}', file=sys.stderr)
    result["test"] = "test"
    print(f'{result}', file=sys.stderr)

result = {}
print(f'variable address at main thread: {hex(id(result))}', file=sys.stderr)
my_worker = lambda : my_func(result)

# execution at another Thread
p = mp.Process(target=my_worker)
p.start()
p.join()

print(f'result at main thread after execution: {result}', file=sys.stderr)

# manual execution
my_worker()
print(f'result at main thread after manual execution: {result}', file=sys.stderr)

print(sys.version)

and the output is:

variable address at main thread: 0x6ffffff39580
variable address at worker: 0x6ffffff39580
{'test': 'test'}
result at main thread after execution: {}
variable address at worker: 0x6ffffff39580
{'test': 'test'}
result at main thread after manual execution: {'test': 'test'}
3.9.16 (main, Mar  8 2023, 22:47:22)
[GCC 11.3.0]

My expectations were that result dictionary would show the changes done at the worker but it does not.

What am I doing wrong?

like image 960
Francisco Javier Rojas Avatar asked Feb 25 '26 04:02

Francisco Javier Rojas


1 Answers

You are using multiprocessing.Process. That is not a thread, that is a new process. It will inherit the whole address space of the parent process, but then work on its own copy. You will have to use threading.Thread if you want a thread.

from threading import Thread

def modify_dict():
    result['test'] = 'test'
    print('Result in worker:', result)

result = {}

t = Thread(target=modify_dict)
t.start()
t.join()

print('Result in main thread:', result)

Output:

Result in worker: {'test': 'test'}
Result in main thread: {'test': 'test'}
like image 131
Marco Bonelli Avatar answered Feb 27 '26 18:02

Marco Bonelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!