如何在Flask中启动新线程?线程只能启动一次

时间:2018-01-12 13:18:06

标签: python multithreading flask raspberry-pi

我正在使用Flask webframe控制连接到Raspberry Pi 3的传感器(开始和停止扫描)。一旦我停止扫描(因为设置了事件),我无法启动新线程因为线程可以只开始一次。所以任何提示开始一个具有不同变量名称的新线程?或任何其他选择?

import thread
from flask import Flask, request, url_for, redirect, render_template

def scan(number, duration):
    #Scanner scanning with 2 parameters

class LoopThread(threading.Thread):
    def __init__(self, name, event):
        super(LoopThread,self).__init__()
        self.name = name #can this use as a global variable?
        self.event = event
        self.number = 20
        self.duration = 1

    def run(self):
        print('Starting Thread-'+ str(self.name))
        while not self.event.wait(timeout=1.0):
            self.loop_process()

    def loop_process(self):
        scan(self.number, self.duration)

app = Flask(__name__)

stopevent = threading.Event()
thread = LoopThread(1, stopevent) #what can I change here?

@app.route("/")
def index():
    print("home page")
    return render_template('home.html')

@app.route("/start")
def start():
    thread.start() #how do I change the function variable name everytime?
    return redirect(url_for('index'))

@app.route("/stop")
def stop():
    stopevent.set() #stop the senseor scanning
    thread.join()
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run("0.0.0.0", debug=True)

1 个答案:

答案 0 :(得分:0)

一个快速而肮脏的解决方案是在函数中实例化你的线程,假设你只能运行一个:

stopevent = None
thread = None

@app.route("/")
def index():
    print("home page")
    return render_template('home.html')

@app.route("/start")
def start():
    global stopevent, thread
    if thread is not None:
        return redirect...
    stopevent = threading.Event()
    thread = LoopThread(1, stopevent) #what can I change here?
    thread.start() #how do I change the function variable name everytime?
    return redirect(url_for('index'))

@app.route("/stop")
def stop():
    global stopevent, thread
    if thread is None:
        return redirect....
    stopevent.set() #stop the senseor scanning
    thread.join()
    stopevent = None
    thread = None
    return redirect(url_for('index'))

这将允许您多次启动和停止线程 - 但它不允许多个并行线程。如果这是你想要的,那么你需要别的东西。