How can I share a variable from a thread to my main in python?

I’m trying to share two variables for a comparation in a conditional in my main, but I am getting errors whenever I set the variables as global, saying that the variable was started before global statement.

Here is a peek to the code:

#thread timer for minute
class myMin(Thread):
    def run(self):
        global now
        global timestart
        n=1 
        while True:
            n=1
            timestart = time.time()
            now = time.time()
            while now-timestart <= 10:
                now = time.time()
            print('banana')
            n=0
#thread timer for the hour
class myHour(Thread):
    def run(self):
        global now2
        global timestart2
        m=1
        while True:
            m=1
            timestart2=time.time()
            now2 = time.time()
            while now2-timestart2 <= 20:
                now2 = time.time()
            print('uvas')
            m =0 

mymin=myMin()
myhour=myHour()

#thread execution
mymin.start()  

myhour.start() 

#Main program counting
while True:
    time.sleep(0.5)
    global m
    global n 
    count = count+1
    countperhour=countperhour+1
    countpermin=countpermin+1
    if m == 0:
        copm = countpermin
        countpermin=0
    if n == 0:
        coph=countperhour
        countpermin=0

>Solution :

You shouldn’t be declaring global m, n inside your loop.
There are other improvements that can be done to your code but below one runs

from threading import Thread
import time
#thread timer for minute
class myMin(Thread):
    def run(self):
        global now
        global timestart
        n=1
        while True:
            n=1
            timestart = time.time()
            now = time.time()
            while now-timestart <= 10:
                now = time.time()
            print('banana')
            n=0
#thread timer for the hour
class myHour(Thread):
    def run(self):
        global now2
        global timestart2
        m=1
        while True:
            m=1
            timestart2=time.time()
            now2 = time.time()
            while now2-timestart2 <= 20:
                now2 = time.time()
            print('uvas')
            m =0


count = 0
countperhour = 0
countpermin = 0

global m
global n
m, n = 0,0
mymin=myMin()
myhour=myHour()

#thread execution
mymin.start()

myhour.start()

#Main program counting
while True:
    time.sleep(0.5)
    count = count+1
    countperhour=countperhour+1
    countpermin=countpermin+1
    if m == 0:
        copm = countpermin
        countpermin=0
    if n == 0:
        coph=countperhour
        countpermin=0

Leave a Reply