python封装线程类(启动、终止、查看线程状态)


一、简单说明

  1. 将启动、终止和查看线程状态的方法封装成类
  2. 声明时传入要启动的方法
  3. 通过 start、stop 和 state 执行启动、终止 和 查看状态

二、实现步骤

# encoding: utf-8

import time
import threading
import inspect
import ctypes


class MyThreadFunc(object):
    '''
    手动终止线程的方法
    '''
    def __init__(self, func, argsTup):
        self.myThread = threading.Thread(target=func, args=argsTup)

    def start(self):
        print('线程启动')
        self.myThread.start()

    def state(self):
        status = self.myThread.is_alive()
        print('线程状态: {0}'.format(status))
        return status

    def stop(self):
        print('线程终止')
        try:
            for i in range(5):
                self._async_raise(self.myThread.ident, SystemExit)
                time.sleep(1)
        except Exception as e:
            print(e)

    def _async_raise(self, 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")


if __name__ == '__main__':

    # 定义一个读秒器
    def second_count(arg1, arg2):
        i = 0
        while True:
            i += 1
            print("{}-{}: {}".format(arg1, arg2, i))
            time.sleep(1)

    # 声明一个线程类
    mythread = MyThreadFunc(second_count, ("好耶", "haoye"))

    # 启动 --------------------------------------
    mythread.start()

    # 等待三秒
    time.sleep(3)

    # 查看线程状态
    mythread.state()

    # 等待三秒
    time.sleep(3)

    # 终止线程 ----------------------------------
    mythread.stop()

    # 等待三秒
    time.sleep(3)

    # 再次查看线程状态
    mythread.state()

三、测试

在这里插入图片描述
ps:python3.2 之后可以使用 concurrent.futures,该模块在 python 的多线程 threading、多进程multiprocesssing 上进一步封装,实现了进程池和线程池,可以参考这篇文章 https://blog.csdn.net/weixin_43721000/article/details/128177331

  • 3
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

什么都干的派森

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

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

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

打赏作者

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

抵扣说明:

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

余额充值