python线程如何终止线程_Python多线程如何终止??

本帖最后由 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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值