0

The original code was

import time, threading

balance = 0

def change_it(n):
    global balance
    balance = balance + n
    balance = balance - n

def run_thread(n):
    for i in range(2000000):
        change_it(n)

t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))

t1.start()
t2.start()
t1.join()
t2.join()
print(balance)

Which gave random results cause the threads were influencing each other But when I tried

t1 = threading.Thread(target=run_thread(5))
t2 = threading.Thread(target=run_thread(8))

it worked properly every time. Why are they different?

1 Answer 1

1

Your second attempt does not actually do any threading. Instead of launching threads, your commands execute your run_thread function on the spot. This is why you have to pass parameters to your threaded function with the args tuple for it to work right. If you state

target=run_thread(5)

target gets the return value of the execution of run_thread(5), which in this case is None as your function does not return anything - but it of course does the calculations within the function when it executes it to get the return value.

This also means your second attempt does not run the tasks in parallel. They are run sequentially one after another.

Sign up to request clarification or add additional context in comments.

2 Comments

oh, I see. I thought the threading.Thread(Target=something()) can also define a thread. Thank you for answering
It could. You could use that construction but then your something() must return the function to be called. This could be useful in some occasions but it is not related to your issue here. In your case you have to use the args structure to pass parameters if and when it is something that will be executed in the thread.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.