I having using python now for about a year and am fairly familiar with it. Though I am quite new to threads and am a little confused by what data threads share.
I have been reading through stuff online which all seem to agree that threads share the same memory space. Though in trying to demonstrate this to myself, it seems I have an incorrect understanding of how this sharing works.
I wrote a short script to just add one to a local variable three times. I create two threads at a time using the same function. I would have thought that due to a shared memory the X variable in one thread would also be increased while it sleeps due to another thread increasing its own X, and vice versa. So after the second loop of thread one where x=2 while thread two sleeps, I would have thought thread two would come out of its sleep with x = 2 and not x = 1. Though as the order of the printed statements suggests, the variables are not shared between the threads.
My question is if you have multiple threads running at once using the same function, will the variables in each thread be kept separate every time throughout the program running (provided no globals are defined)? And then what exactly does this shared memory mean?
Any guidance on the issue (or general threading advice) would be greatly appreciated.
import threading
from time import sleep
def increase(x):
for i in range(3):
print(f"[{threading.currentThread().getName()}] X is {x}")
x += 1
print(f"[{threading.currentThread().getName()}] X is now {x} after increase")
sleep(0.5)
print(f"[{threading.currentThread().getName()}] X is now {x} after sleep")
return x
def main():
x = 0
first = threading.Thread(name="Thread One", target=increase,args=([x]))
second = threading.Thread(name="Thread Two", target=increase,args=([x]))
first.start()
second.start()
first.join()
second.join()
if __name__ == "__main__":
main()
And the result is:
[Thread One] X is 0
[Thread One] X is now 1 after increase
[Thread Two] X is 0
[Thread Two] X is now 1 after increase
[Thread Two] X is now 1 after sleep[Thread One] X is now 1 after sleep
[Thread One] X is 1
[Thread One] X is now 2 after increase
[Thread Two] X is 1
[Thread Two] X is now 2 after increase
[Thread One] X is now 2 after sleep[Thread Two] X is now 2 after sleep
[Thread Two] X is 2
[Thread Two] X is now 3 after increase
[Thread One] X is 2
[Thread One] X is now 3 after increase
[Thread One] X is now 3 after sleep[Thread Two] X is now 3 after sleep