Search code examples
pythonmultithreadingglobal-variables

One thread does not effect another other thread?


Just forget about title....

I am trying, to print global variables with 5 iterations for each thread. On each iteration, global variables value increment by 5000.
I want that each thread reads the same variable value as previous or reads variable value by one thread does not effect the variable value read by another thread.

Example:

If thread-1 reads f_price = 1000 and l_price = 6000, then after increment f_price = 6000 and l_price = 11000 became respectively. So increment by thread-1 does not effect the value reads by the thread-2. Thread-2 first read the same variable values f_price = 1000 and l_price = 6000. and so on.....

from threading import Thread
import threading
from time import sleep

# variables

f_price = 1000
l_price = 6000


def main():
    global f_price, l_price

    print(threading.currentThread().getName(), 'just Start the Job')
    
    for each_iteration in range(1,5):
        print('Hi I am', threading.currentThread().getName(), 'Price Lies Between is:', f_price, '-', l_price)
        print('\n')

        f_price = l_price
        l_price += 5000

    print(threading.currentThread().getName(), 'Finish the Job')


thread1 = Thread(target=main)
thread2 = Thread(target=main)
thread3 = Thread(target=main)

thread1.start()
thread2.start()
thread3.start()

thread1.join()
thread2.join()
thread3.join()

Solution

  • Have main accept two arguments rather than using (and modifying) the global variables.

    from threading import Thread
    import threading
    from time import sleep
    
    # variables
    
    f_price = 1000
    l_price = 6000
    
    
    def main(f_price, l_price):
    
        print(threading.currentThread().getName(), 'just Start the Job')
        
        for each_iteration in range(1,5):
            print('Hi I am', threading.currentThread().getName(), 'Price Lies Between is:', f_price, '-', l_price)
            print('\n')
    
            f_price = l_price
            l_price += 5000
    
        print(threading.currentThread().getName(), 'Finish the Job')
    
    
    thread1 = Thread(target=main, args=(f_price, l_price)
    thread2 = Thread(target=main, args=(f_price, l_price)
    thread3 = Thread(target=main, args=(f_price, l_price)
    
    thread1.start()
    thread2.start()
    thread3.start()
    
    thread1.join()
    thread2.join()
    thread3.join()