我使用Flask webframe控制一个传感器(开始和停止扫描),它连接到一个树莓皮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)
一个快速而肮脏的解决方案是在函数中实例化线程,假设只能运行一个线程:
这将允许您多次启动和停止线程,但不允许多个并行线程。如果这是你想要的,那么你需要别的东西。在
相关问题 更多 >
编程相关推荐