【发布时间】:2023-03-20 23:16:01
【问题描述】:
之前有人问过类似的问题,但没有提供正确的答案。
我正在尝试编写代码来测试 Python 中的线程,其中每秒钟都会有一个代码滴答作响。我试图让名为“clicking”的ticker函数在一个线程中运行,该线程的输出每秒不断增加1。
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),但没有奏效。
【问题讨论】:
标签: python multithreading time ticker