I have created an app that controls LED lighting. I wanted to have support for color changing patterns. In order for other parts of the program to work, this section of code is being executed in a separate thread. Unfortunately, I cannot make changes to the color-cycling pattern through my web-based interface (flask) once the thread is started. Is there a way for me to pass the variable data to the thread (color1, color2, and speed)? Also, the the thread is constructed in such a way that it inherits a stop method from its parent class.
app.py
from flask import Flask, render_template, request, jsonify
...
cycleToggle = "on"
@app.route("_/start")
def _start():
global cycleToggle
global thread
if cycleToggle=="on":
thread = Pins.cyclecolors()
thread.start()
cycleToggle = "off"
return render_template("cyclecolors.html") #flask
@app.route("/_stop")
def _stop():
global cycleToggle
cycleToggle = "on"
thread.stopit()
return render_template("cyclecolors.html")
@app.route("/_updateCycle")
def _updateCycle():
color1 = request.args.get('color1')
color2 = request.args.get('color2')
speed = request.args.get('speed')
Pins.updateCycle(color1,color2,speed)
Pins.py
import threading
...
class StoppableThread(threading.Thread):
def __init__(self):
super(StoppableThread, self).__init__()
self._stopper = threading.Event()
def stopit(self):
self._stopper.set()
def stopped(self):
return self._stopper.is_set()
class cyclecolors(StoppableThread):
def __init__(self):
StoppableThread.__init__(self)
def run(self):
while not self.stopped():
## THIS IS WHERE THE COLOR CYCLING CODE WOULD GO THAT UTILIZES
## THE color1, color2, AND speed VARIABLES.
def updateCycle(color_1, color_2, speed_a)
global color1
global color2
global speed
color1 = color_1
color2 = color_2
speed = speed_a
return
I understand that using global variables with threads is frowned upon; however, the thread is not changing the variables. It simply needs to read them.
Is there a way for me to pass the variable data to the thread (color1, color2, and speed)?
Sure, take a look at the Queues .
What you need to do is let your producer push data such as color, speed and so on in the queue and let your consumer (threads) pull those variables and work on them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.