Ale*_*lex 4 python multithreading
python模块线程有一个对象Thread,用于在不同的线程中运行进程和函数.这个对象有一个start方法,但没有stop方法.什么是Thread无法阻止我调用简单stop方法的原因?我可以想象使用这种join方法不方便的情况......
start可以是通用的并且有意义,因为它只是触发线程的目标,但是泛型会stop做什么?根据您的线程正在做什么,您可能必须关闭网络连接,释放系统资源,转储文件和其他流,或任何其他自定义,非平凡的任务.任何能够以通用方式完成大部分这些事情的系统都会给每个线程增加太多的开销而不值得,并且会如此复杂并且通过特殊情况突然发现它几乎不可能工作用.您可以跟踪所有创建的线程,而无需将join它们放在主线程中,然后检查它们的运行状态,并在主线程自行关闭时传递它们某种终止消息.
绝对可以实现一个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()
Run Code Online (Sandbox Code Playgroud)
的Thread3类似乎运行代码比快大约33%的Thread2类.
以可靠的方式杀死线程并不是一件容易的事.想想所需的清理:哪些锁(可能与其他线程共享!)应该自动释放?否则,你很容易陷入僵局!
更好的方法是自己实现正确的关闭,然后设置
mythread.shutdown = True
mythread.join()
Run Code Online (Sandbox Code Playgroud)
停止线程.
当然你的线程应该做类似的事情
while not this.shutdown:
continueDoingSomething()
releaseThreadSpecificLocksAndResources()
Run Code Online (Sandbox Code Playgroud)
经常检查关机标志.或者,您可以依赖特定于操作系统的信号机制来中断线程,捕获中断,然后清除.
该清理是最重要的部分!