带定时While循环的Python线程

之前也曾提出过类似的问题,但没有提供正确的答案。

我正在尝试编写代码以测试Python中的线程,其中的代码每秒钟跳动一次。我试图使名为“ clicking”的自动报价功能在一个线程中运行,该线程的输出连续每秒递增一。

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),但没有用。

iCMS 回答:带定时While循环的Python线程

问题是您没有在while循环中更新curr变量。但是请注意,当您在while循环中编写“ curr = q.get()”时,它将获得队列中的下一个值,而不是最后一个值(正如我想的那样)。我想更简单的方法是使用time.time()

跟踪while循环内的秒数增量
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')

这样您也可以正确退出,请注意,即使循环中断,在示例中线程仍将继续。

但是如果您想维护后台线程,我建议创建一个类并为当前计数器和运行条件存储类变量。

本文链接:https://www.f2er.com/1511816.html

大家都在问