i am learning about threads and got one thing confusing.
from threading import Thread
from time import sleep
global a
a=0
def th1():
lasta=0
while(a<200):
if(a!=lasta):
lasta=a
print(a)
thrd=Thread(target=th1)
print(a)
thrd.start()
for i in range (1,200):
a+=1
sleep(0)
this prints numbers from 0 to 199, but
from threading import Thread
from time import sleep
global a
a=0
def th1():
lasta=0
while(a<200):
if(a!=lasta):
lasta=a
print(a)
thrd=Thread(target=th1)
print(a)
thrd.start()
for i in range (1,200):
a+=1
this code only prints 0 and 199.
I think what's happening is that in second code there's not the (lats say) stop statement that would make program execute different portion of the code while first one stops the loop and gives another thread the possibility to execute. then it checks if 0 seconds went and continues from for loop. i dont know if im right, please if you could help me explain what is really going on i would be glad. also how can i master this kind of things? for example to run two threads continuously and let them do stuff according to one global variable. because as i clearly see even though i'm using different thread, they aren't really doing stuff together, they are still waiting for each other
Thanks!
Your specific question is quite correct: a 0-second time-out is quite different from no statement at all. As you guess, this suspends the running thread and allows another thread to receive control of the CPU.
If you use merely multi-threading, then you get the interleaving situation you describe here: you have two logical execution threads, but only one logical processor. For parallel processing, you need multi-processing. There are many tutorials and examples available on line; simply search for "Python multiprocessing tutorial".
Your request "how can i master this kind of things?" is far too general to be a Stack Overflow question. You master this knowledge as you master any knowledge: you find materials that match your learning styles, work through those materials, and practice.