【问题标题】:Threading in Python with Timed While Loop在 Python 中使用 Timed While 循环进行线程化
【发布时间】: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


    【解决方案1】:

    问题是您没有在 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')
    

    这样你也可以正常退出,注意在你的例子中,即使循环中断线程继续。

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

    【讨论】:

    • 我专门研究了为此目的使用多线程,其中在主代码上玩游戏时,点击器功能在备用线程上运行。这是作为一个实验。谢谢。
    猜你喜欢
    • 2020-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    相关资源
    最近更新 更多