线程时,打印功能会加快线程速度

2024-10-02 12:28:15 发布

您现在位置:Python中文网/ 问答频道 /正文

在使用Tkinter设置GUI时遇到了一个奇怪的交互。我有两个线程在程序的后台运行,它们在GUI初始化之后启动

def init(top, gui, *args, **kwargs):
    ...
    threading.Thread(target=BackendTask).start()  ## polls sensors
    threading.Thread(target=FrontendTask).start() ## updates GUI

两个任务的简化版本

def BackendTask():
    global BTaskRefRate
    BTaskRefRate = 0
    while True:
        startTime = time.time()
        for i in range(0, len(strut)):
            ... ## polling sensors
            if i == len(strut):
                BTaskRefRate = time.time() - startTime
                #print(i)
                #sys.stdout.flush()

def FrontendTask():
    global FTaskRefRate
    FTaskRefRate = 0
    while True:
        startTime = time.time()
        ... ## Updates to 50+ widgets
        FTaskRefRate = time.time() - startTime

在函数BackendTask()的第9行注释掉了print(i)FrontendTask()以~300ms完成每个循环

在函数BackendTask()的第9行取消注释print(i)FrontendTask()以~50ms完成每个循环

无论打印是否被注释掉,BackendTask()以~3ms的速度运行

为什么从一个线程打印会导致另一个线程显著加快


Tags: targettimedefgui线程threadstartprint

热门问题