Search code examples
python-3.xmultithreadingpython-multithreadingcpython

Is it necessary to pass a shared variable explicitly to a threading function in Python using args in Threads()or directly access it?


Is it necessary to pass a shared variable explicitly to a threading function like i have shown below (First example ) in Python 3.10+

Os is Windows 10,Python interpreter is CPython

or

is it ok to directly access the shared variable from the function as shown in the second code example.

# First example
# passing Arguments to the threading function using args 

import time
import threading


def update_list_A(var_list):
         var_list.append('A')

shared_list =[]

t1 = threading.Thread(target = update_list_A, args = (shared_list,)) #usings args to send shared variable

t1.start()
t1.join()

print(shared_list)

+-----------------------------+

#second example
#directly accessing the shared variable from the threading function 

import time
import threading


def update_list_A():
         shared_list.append('A')

shared_list =[] #shared List 

t1 = threading.Thread(target = update_list_A, )

t1.start()
t1.join()

print(shared_list)

What is the correct way to access the shared variable, is it through args or directly?


Solution

  • I'd say it depends on context:

    • For short code where there are few shared variables, and they are declared and used in a small section, you should access it directly. This makes the code simpler.

    • For longer code or with complicated flow, passing the shared variable via thread arguments allows you to formalize what values the thread will access. This helps ensure you don't access values you didn't mean to, makes testing easier, and pushes you towards minimizing the number of shared variables.

    It's a similar argument to global variables.