Why do threads present inconsistent results? -Python

Viewed 29

I have this code:

import threading
import time

#Starting a timer
start = time.time()


def zero():
    for i in range(0,10):
        print(0)


def one():
    for i in range(0,10):
        print(1)


#threads
t0 = threading.Thread(target=zero)
t1 = threading.Thread(target=one)

t0.start()
t1.start()

#To run the threads before any thing bellow.
t0.join()
t1.join()

end = time.time()
print(f"The program took {round(end - start,3)} seconds to finish.")

RESULTS:

(0): 0 0 0 0 0 0 1 0 0 0 0 1 1 1 1 1 1 1 1 1

(1): 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1

(2): 0 0 0 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 1 1

Shouldn't it be 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1?

EDIT:

Thanks, it was answered by this: Execution order of multiple threads

And: What makes the execution order of threads unpredictable?

And the comments too.

0 Answers
Related