python中stop_thread_为什么python threading.Thread对象有“start”,而没有“stop”?

完全可以实现如下示例代码所示的Thread.stop方法:import threading

import sys

class StopThread(StopIteration): pass

threading.SystemExit = SystemExit, StopThread

class Thread2(threading.Thread):

def stop(self):

self.__stop = True

def _bootstrap(self):

if threading._trace_hook is not None:

raise ValueError('Cannot run thread with tracing!')

self.__stop = False

sys.settrace(self.__trace)

super()._bootstrap()

def __trace(self, frame, event, arg):

if self.__stop:

raise StopThread()

return self.__trace

class Thread3(threading.Thread):

def _bootstrap(self, stop_thread=False):

def stop():

nonlocal stop_thread

stop_thread = True

self.stop = stop

def tracer(*_):

if stop_thread:

raise StopThread()

return tracer

sys.settrace(tracer)

super()._bootstrap()

################################################################################

import time

def main():

test = Thread2(target=printer)

test.start()

time.sleep(1)

test.stop()

test.join()

def printer():

while True:

print(time.time() % 1)

time.sleep(0.1)

if __name__ == '__main__':

main()

Thread3类运行代码的速度似乎比Thread2类快33%。

附录:

充分了解Python的C API和ctypes模块的使用,可以编写一种更有效的方法来在需要时停止线程。使用sys.settrace的问题是跟踪函数在每条指令之后运行。如果在需要中止的线程上引发异步异常,则不会产生执行速度惩罚。以下代码在这方面提供了一些灵活性:#! /usr/bin/env python3

import _thread

import ctypes as _ctypes

import threading as _threading

_PyThreadState_SetAsyncExc = _ctypes.pythonapi.PyThreadState_SetAsyncExc

# noinspection SpellCheckingInspection

_PyThreadState_SetAsyncExc.argtypes = _ctypes.c_ulong, _ctypes.py_object

_PyThreadState_SetAsyncExc.restype = _ctypes.c_int

# noinspection PyUnreachableCode

if __debug__:

# noinspection PyShadowingBuiltins

def _set_async_exc(id, exc):

if not isinstance(id, int):

raise TypeError(f'{id!r} not an int instance')

if not isinstance(exc, type):

raise TypeError(f'{exc!r} not a type instance')

if not issubclass(exc, BaseException):

raise SystemError(f'{exc!r} not a BaseException subclass')

return _PyThreadState_SetAsyncExc(id, exc)

else:

_set_async_exc = _PyThreadState_SetAsyncExc

# noinspection PyShadowingBuiltins

def set_async_exc(id, exc, *args):

if args:

class StateInfo(exc):

def __init__(self):

super().__init__(*args)

return _set_async_exc(id, StateInfo)

return _set_async_exc(id, exc)

def interrupt(ident=None):

if ident is None:

_thread.interrupt_main()

else:

set_async_exc(ident, KeyboardInterrupt)

# noinspection PyShadowingBuiltins

def exit(ident=None):

if ident is None:

_thread.exit()

else:

set_async_exc(ident, SystemExit)

class ThreadAbortException(SystemExit):

pass

class Thread(_threading.Thread):

def set_async_exc(self, exc, *args):

return set_async_exc(self.ident, exc, *args)

def interrupt(self):

self.set_async_exc(KeyboardInterrupt)

def exit(self):

self.set_async_exc(SystemExit)

def abort(self, *args):

self.set_async_exc(ThreadAbortException, *args)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值