Python中带计时While循环的线程
早些时候也有人问过类似的问题,但没有给出正确答案 我试图用Python编写测试线程的代码,在这种代码中,每秒钟都有一个滴答声。我试图让名为“clicking”的ticker函数在一个线程中运行,该线程的输出每秒递增一次Python中带计时While循环的线程,python,multithreading,time,ticker,Python,Multithreading,Time,Ticker,早些时候也有人问过类似的问题,但没有给出正确答案 我试图用Python编写测试线程的代码,在这种代码中,每秒钟都有一个滴答声。我试图让名为“clicking”的ticker函数在一个线程中运行,该线程的输出每秒递增一次 import time import threading import queue q = queue.Queue() apple = 0 orange = 0 rate = 1 clix = 0 def clicking(clix, rate): whi
import time
import threading
import queue
q = queue.Queue()
apple = 0
orange = 0
rate = 1
clix = 0
def clicking(clix, rate):
while True:
time.sleep(1)
clix += rate
q.put(clix)
threading.Thread(target=clicking, args=(clix, rate)).start()
curr = q.get()
print(curr)
print('\nClicker Starting...')
endgame = False
while not endgame:
print(f'Clix: {curr}')
print('1. Apple : 10 clix | 2. Orange : 8 clix | 3. Exit')
ch = int(input('\nPurchase ID: '))
if ch == 1 and curr >= 10:
print(f'You have {curr} clix.')
print('Got an Apple!')
apple += 1
rate += 1.1
curr -= 10
elif ch == 2 and curr >= 8:
print('Got an Orange!')
orange += 1
rate += 1.2
curr -= 8
elif ch == 3:
endgame = True
stopflag = True
else:
print('Need more Clix')
但我的otuput始终为1,而不是按定义的速率每秒递增。我错过了什么?我甚至尝试了
return clix
来代替q.put(clix)
,但没有成功。问题是您没有在while循环中更新curr变量。但是请注意,当您在while循环中写入“curr=q.get()”时,它将获得队列中的下一个值,而不是最后一个值(我想这是您想要的)。我想更直接的方法是使用time.time()跟踪while循环中的秒增量
通过这种方式,您也可以正确退出,请注意,在您的示例中,即使循环中断,线程也会继续
但是,如果您想维护后台线程,我建议为当前计数器和运行条件创建一个类并存储类变量。我专门研究了多线程的用法,其中clicker函数在备用线程上运行,而游戏在主代码上玩。这是一个实验。非常感谢。
import time
apple = 0
orange = 0
rate = 1
clix = 0
curr = 0
last_ts = time.time()
print('\nClicker Starting...')
endgame = False
while not endgame:
ts = time.time()
curr += (ts - last_ts) * rate
last_ts = ts
print(f'Clix: {curr:.0f}')
print('1. Apple : 10 clix | 2. Orange : 8 clix | 3. Exit')
ch = int(input('\nPurchase ID: '))
if ch == 1 and curr >= 10:
print(f'You have {curr:.0f} clix.')
print('Got an Apple!')
apple += 1
rate *= 1.1 # I guess you meant x1.1
curr -= 10
elif ch == 2 and curr >= 8:
print('Got an Orange!')
orange += 1
rate *= 1.2 # I guess you meant x1.2
curr -= 8
elif ch == 3:
endgame = True
stopflag = True
else:
print('Need more Clix')