Python:杀死循环线程的最佳实践

2024-05-18 14:25:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用WxPython向用户展示某种形式的GUI。我有一个开/关切换,它执行grep,并每n秒返回一次行计数

如果我在窗口内执行此循环,窗口将变得无响应,用户无法再关闭按钮。所以,当我在谷歌上搜索如何防止这种情况发生时,一种常见的做法似乎是线程化。但是,我遇到了这样的引用:“一般来说,突然杀死线程被认为是一种糟糕的编程实践”,而这正是我希望我的用户能够做到的

因此,如果我不应该在线程完成之前停止线程,那么设置它的最佳实践是什么

到目前为止,我所拥有的:

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()

这适用于启动线程(我的GUI没有“挂起”),但当我关闭开关时,会出现错误

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

这条线还在继续。。我想我的停止不能调用已经启动的线程或其他东西。但是再说一次,我应该用线程来实现这一点,还是用其他方式来实现

提前谢谢


Tags: run用户selftrueifdefguiwindow

热门问题