I am trying to do a simple threading but i'm not sure why it doesn't work. i created 2 basic functions hat each one prints "hello" 5 times, and thread for each one of the, but for some reason they run one after another and not concurrently.
this is the code:
def check1():
for i in range(5):
print("hello 1")
def check2():
for i in range(5):
print("hello 2")
t1 = threading.Thread(target=check1)
t2 = threading.Thread(target=check2)
t1.start()
t2.start()
i'm getting:
hello 1
hello 1
hello 1
hello 1
hello 1
hello 2
hello 2
hello 2
hello 2
hello 2
Lets imagine you have 3 tasks: washing the dishes, tidying your room, and cleaning the windows. You can do it in any order you want, you may start 1 and pause it and do another before finishing it. Threads are similar to tasks for computers, they have to execute all of them and they will do it in any order they want and swapping between them as they want.
Now imagine the tasks you have are pressing the green button, pressing the red button and pressing the yellow button. The tasks are so simple that is makes no sense once you start pressing a button to stop before finishing, go to another task and then come back. The tasks are so simple that will be finished before you even think of changing to another task. The tasks you provided to the computer are that trivial. Writting 5 times hello
is like pushinjg a button, it won't even consider swapping to another thread. If you make it sleep for 100 ms between every hello
, while it is waiting it will ask itself if it has another task to do and execute it, but if you let it print the 5 hello
s in a row it will finish it instantly and after that, it will ask itself what other tasks it has.
When tasks are much more complex, you will not need to add sleeps, it will swap tasks by itself.