说明的问题
经常的时候,我们需要实现对额外的线程的启动与停止,例如,我们需要有的时候进行建立tcp的连接接收数据,有的时候需要保证系统资源,我们需要暂时停止当前的线程,因此需要实现对线程的启停。
线程停止函数
同时可以参考,之前我的一篇blog:
https://blog.csdn.net/weixin_42066185/article/details/106670921
import inspect
import ctypes
def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
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")
def stop_thread(thread):
# try:
_async_raise(thread.ident, SystemExit)
# except "invalid thread id":
# print("Already clear the thread")
线程的建立与重新的启动
def __init__():
self.test_thread = threading.Thread(target=self.test_subthread)
self.test_thread.start()
self.qiting()
def qiting(self):
time.sleep(10)
stop_thread(self.test_thread)
print('we have stop this thread')
time.sleep(5)
print('we are goint to start')
# self.test_thread.start()
self.test_thread = threading.Thread(target=self.test_subthread)
self.test_thread.start()
def test_subthread(self):
context = zmq.Context()
zmqsub = context.socket(zmq.SUB)
zmqsub.setsockopt(zmq.SUBSCRIBE, b'')
# self.subaddr='tcp://192.168.127.200:10011'
subaddr = 'tcp://192.168.127.201:5011'
# self.subaddr='inproc://iiii'
print('in the thread init')
# zmqsub.connect(subaddr)
while True:
time.sleep(1)
print('it is already 1s')
结果验证
首先系统运行了约10s钟,实现了测试线程的停止,然后等待3s 后实现了线程的重新的启动。