|
发表于 2018-3-19 19:27:38
|
显示全部楼层
本帖最后由 yuexing 于 2018-3-19 19:30 编辑
# 不需要循环判断 可以立即终止线程,来终止线程的方法来着网络
import wx
import time
import threading, inspect, ctypes
def functest():
def printex(str):
while True:
for dot in ['.', '..', '...']:
yield print(str + ' ' + dot)
generator = printex('函数')
while True:
next(generator)
time.sleep(0.2)
class MyThread(threading.Thread):
def __init__(self, func, args=(), kwargs=None):
threading.Thread.__init__(self)
if kwargs is None:
kwargs = {}
self.func = func
self.args = args
self.kwargs = kwargs
def run(self):
# print('子线程id', self.ident)
self.func(*self.args, **self.kwargs)
def stop_thread(self):
if self.is_alive():
self.__async_raise(self.ident, SystemExit)
else:
logger.info('线程没有存活')
def __async_raise(self, tid, exctype):
"""raises the exception, performs cleanup if needed"""
# print('被停止的线程id', tid)
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
class Frame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, size=(200, 100))
panel = wx.Panel(self)
boxsizer = wx.BoxSizer(wx.HORIZONTAL)
self.startbutton = wx.Button(panel, label='启动按钮')
self.endbutton = wx.Button(panel, label= '终止按钮')
boxsizer.Add(self.startbutton, 1, wx.EXPAND)
boxsizer.Add(self.endbutton, 1, wx.EXPAND)
panel.SetSizer(boxsizer)
class App(wx.App):
def OnInit(self):
frame = Frame()
frame.Show()
frame.startbutton.Bind(wx.EVT_BUTTON, self.startprocess)
frame.endbutton.Bind(wx.EVT_BUTTON, self.endprocess)
return True
def startprocess(self, event):
print('启动事件启动了')
self.thrd = MyThread(func=functest)
self.thrd.start()
def endprocess(self, event):
print('终止事件启动了')
self.thrd.stop_thread()
if __name__ == '__main__':
app = App()
print('app线程id: ', threading.get_ident())
app.MainLoop()
|
|