我試圖在我的主要條件中共享兩個變數以進行比較,但是每當我將變數設定為全域時都會出現錯誤,說變數是在全域陳述句之前啟動的。
這是代碼的一瞥:
#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
uj5u.com熱心網友回復:
您不應該在回圈中宣告 global 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481893.html
標籤:Python 多线程 python-多线程
下一篇:執行緒混淆中的共享記憶體
