python线程在不循环时是否自动终止?

2024-05-16 09:39:41 发布

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

如果python中的线程没有循环,它们会自动终止吗?你知道吗

我的googlefoo今天显然是垃圾。但基本上:我有一个运行在pi上的小型热敏打印机,它还为alexa服务托管了一个webhook。打印机需要在alexa说话的同时运行。每次调用launch函数时,它都会触发线程并执行它的操作。我不想阻止主程序,但这会产生一堆永远的线程吗?或者他们只是完成任务然后停下来?这也是超级暴力。你知道吗

def printFortune():
    fortune = makeFortune()
    print("printFortune!",fortune)
    printer.println(fortune[0])
    printer.println()
    printer.println(fortune[1])
    printer.println()
    printer.println(fortune[2])
    printer.println()
    printer.feed(3)
    printer.setDefault()

### APP THINGS #####################

@app.route('/',methods=['GET','POST'])
def index():
    return "hello! This is an alexa test."

### ALEXA THINGS #####################

@ask.on_session_started
def new_session():
    log.info('new session started')
    log.info(request.locale)
    beep = request.locale
    print(beep)

@ask.launch
def launch():
    t = Thread(target=printFortune)
    t.start()
    to_say = "This is a very long response that is not the response that's being printed" 
    return statement(to_say)


@ask.intent('AMAZON.HelpIntent')
def help():
    return question("helping").reprompt("helping")

@ask.intent('AMAZON.StopIntent')
def stop():
    return statement("stopping")

@ask.intent('AMAZON.CancelIntent')
def cancel():
    return statement("canceling")

@ask.session_ended
def session_ended():
    log.debug("Session Ended")
    print("session ended")
    return "{}", 200

if __name__ == '__main__':
    app.config['ASK_VERIFY_REQUESTS'] = False
    app.run(host='0.0.0.0', port=5000, debug=True, use_reloader=False)

Tags: logappreturnissessiondeflaunch线程
2条回答

根据文件:

Once the thread’s activity is started, the thread is considered ‘alive’. It stops being alive when its run() method [or target method] terminates – either normally, or by raising an unhandled exception.

见:https://docs.python.org/3.7/library/threading.html#threading.Thread.run

在示例的上下文中,您创建的每个线程将在该线程的printFortune()方法完成时终止(或引发异常)。你知道吗

根据Threading的官方文件:

Once the thread’s activity is started, the thread is considered ‘alive’. It stops being alive when its run() method terminates – either normally, or by raising an unhandled exception. The is_alive() method tests whether the thread is alive.

因此,为了回答您的问题,线程对象将在其相应的run()方法终止时终止。您可以使用threading.Thread.is_alive()来确定线程的run()方法是否已完成。你知道吗

文档接着讨论了普通线程和守护进程线程之间的区别(它们在终止策略上确实有区别),但这似乎不适用于您发布的示例。你知道吗

相关问题 更多 >