在键盘中断退出时干净地停止 python 线程

Cleanly stop a python thread on keyboard break exit

我正在使用 python 线程检查本地 SQL 数据库中的值更改。我在主程序上有错误处理来处理 Ctrl+C 键盘中断。这会停止主代码,但线程会继续运行。当按下 ctlr+c 时,我应该如何干净地停止线程。谢谢。 主题是这样的:

def getVars():
    global setTemp
    global pidControl
    while True:
        dB = MySQLdb.connect(host="localhost",
                             user="pythonUser",
                             passwd="password123",
                             db="pythonProg")

        cur = dB.cursor()
        cur.execute("SELECT * FROM PiBQ_Temp WHERE tempKey = 1")
        for field in cur:
            fetchTemp = field[1]
            print ("Thread getVars checked temp: " + fetchTemp)

        # Check to see if fetchTemp is different to setTemp and update pid if needed
        if fetchTemp != setTemp:
            setTemp = fetchTemp
            pidControl.setPoint(setTemp)
        time.sleep(5)

它在主 try: 语句中被这样调用:

# Start the getVars thread
t = threading.Thread(target=getVars, args=())
t.start()
print "Thread started: getVars"

错误处理是这样的:

except (KeyboardInterrupt, SystemExit):
    os.system('clear')
    print ('ctrl+C pressed. \nProgramme complete')
    dB.commit()
    dB.close()
    screen.lcd_cleanup()
    GPIO.cleanup()

一种常用的方法是创建一个全局变量,例如pendingExit = False 并在 except 处理程序中将其设置为 True,然后 join 工作线程等待其结束。

getVars 中的工作线程必须定期检查 pendingExit 并结束。