I'm new to threading in python and I've began by creating a simple program which uses two threads to print the numbers 1-100. The first thread prints all of the odd numbers and the second thread prints all of the even numbers.
Initially, I encountered a problem where my threads were just printing the numbers as fast as they could, so the numbers weren't always in order. I don't know (and neither have I researched) how to synchronise threads in python so I've implemented a simple technique where I use Boolean flags and switch them on and off, and use a delay to 'sync' the threads.
Looking at my code, I've just realised that my flags have the exact same variable names as my threads.
Why isn't python throwing any errors?
My code:
import time, threading
def printOdd():
global odd, even
for i in range(1, 101, 2):
while not odd:
time.sleep(0.01)
if odd:
print(i)
odd = False
even = True
def printEven():
global odd, even
for i in range(2, 101, 2):
while not even:
time.sleep(0.01)
if even:
print(i)
odd = True
even = False
odd = True
even = False
odd = threading.Thread(target = printOdd)
even = threading.Thread(target = printEven)
odd.daemon = True
even.daemon = True
odd.start()
even.start()