I'm using WxPython to show the user some form of GUI. I have a On/Off toggle that does a grep, and returns the line count the every n seconds.
If I do this loop inside the Window, the window becomes unresponsive and the user cannot toggle the button off anymore. So when I google how to prevent this from happening, one common practice seems to be threading. But, I come across these quotes like "In general, killing threads abruptly is considered a bad programming practice.", and this is exactly what I want my users to be able to do..!
So if I'm not supposed to stop threads before they finish, what is the best practice to set this up?
What I have so far:
def run(stop):
while True:
print('thread running')
time.sleep(2)
if stop():
break
class Window(TLM_lite_GUI.MainFrame):
def __init__(self,parent):
TLM_lite_GUI.MainFrame.__init__(self,parent)
def ExitEvent(self,event):
self.Destroy()
def OnOffEvent(self,event):
OnOff = self.OnOffButton.GetValue()
t1 = threading.Thread(target = run, args =(lambda : stop_threads, ))
if OnOff:
stop_threads = False
t1.start()
else:
stop_threads = True
t1.join()
app = wx.App(False)
Frame = Window(None)
Frame.Show(True)
app.MainLoop()
This works for starting the thread (and my GUI does not 'hang'), but when i toggle the switch OFF I get the error
File "C:\Python36\lib\threading.py", line 1051, in join
raise RuntimeError("cannot join thread before it is started")
RuntimeError: cannot join thread before it is started
And the thread just continues.. I think my stop is not able to call the already started thread or something. But again - should I even be doing this with threading, or should I do it some other way?
Thanks in advance.