pyqt5使用thread 实现多个线程的启动与停止

说明的问题

经常的时候,我们需要实现对额外的线程的启动与停止,例如,我们需要有的时候进行建立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 后实现了线程的重新的启动。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

没有水杯和雨伞的工科男

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值