0

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.

Ronald
  • 172
  • 2
  • 11
  • Read [Is there any way to kill a Thread?](https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread) – stovfl Feb 28 '20 at 15:18
  • @stovfl exactly, the accepted answer starts with 'It is generally a bad pattern to kill a thread abruptly, in Python and in any language'. Does this mean I should not be doing this, or is the way to do it (described below it) a 'good' way of closing threads? The code in that answer is also too complex for me at this point - I don't know how to get it to work.. I'll try to figure it out. – Ronald Feb 28 '20 at 15:35
  • @Ronald Accepted answers are merely what the OP considered the most useful to *them*. There are several other answers there that will do what you want in a simpler way - e.g. [this one](https://stackoverflow.com/a/27261365/984421). – ekhumoro Feb 28 '20 at 15:41

0 Answers0