如何在 python 中将变量从线程共享到我的主线程?

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

我试图在我的 main 的条件中共享两个变量以进行比较,但是每当我将变量设置为全局变量时我都会收到错误消息,说变量是在全局语句之前启动的。

代码如下:

#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

您不应该在循环内声明全局 m, n。 可以对您的代码进行其他改进,但低于一次运行

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