0

I'm learning the concept of race_condition and lock in python multithreading and I spotted this weird behavior

In the following programme

from threading import Thread
import time

value = 0
def increase():
    global value
    local = value
    local += 1
    time.sleep(0.1)
    value = local

print('start value', value)

#create threads
thread1 = Thread(target=increase)
thread2 = Thread(target=increase)

#start threads
thread1.start()
thread2.start()

#join threads
thread1.join()
thread2.join()

print('end value', value)

print('end main')

while creating threads if I don't use parentheses in with function name in target as

thread1 = Thread(target=increase)
thread2 = Thread(target=increase)

I get the result

start value 0
end value 1
end main

which is normal case for race conditions but if I use parentheses as

thread1 = Thread(target=increase())
thread2 = Thread(target=increase())

I get

start value 0
end value 2
end main

which I should get after using lock on threads.. Can somebody explain?

Anmol Virk
  • 3
  • 1
  • 3
  • thread always needs function's name without `()`. if you use `()` then it runs it directly in current process - so it works like `result1 = increase()` `result2 = increase()` `Thread(target=result1)` `Thread(target=result2)` – furas Aug 05 '22 at 11:29

1 Answers1

1

It is not weird behavior but you simply use threads in wrong way - so you ge wrong result.

Thread needs function's name with out ()

If you use () then your code works like

result1 = increase() 
Thread(target=result1)  

result2 = increase()  
Thread(target=result2)

So you run function increase() two times in current process - not in separated threads. And they run one after another - not at the same time like in threads - and there is no race condition.

furas
  • 134,197
  • 12
  • 106
  • 148