threading模块

官方介绍:https://docs.python.org/zh-cn/3.9/library/threading.html

一条简单的线程

loading加了括号会运行方法,而不是成为一条线程
import threading
import time


def loading(i): # 无线循环的一个方法
    while True:
        print('第{}次运行'.format(i))
        i+=1
        time.sleep(3)


if __name__ == '__main__':
    th = threading.Thread(target=loading,args=(0,))    # loadong加了括号会直接运行,即使不start也会运行
    th.start()
    print("会运行到这儿嘛")

  

Thread函数

看看这个类有哪些参数我们需要填的参数又有哪些吧

 

 

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

 

参数如下:

group

用于分组,扩展 ThreadGroup 类实现而保留。默认 None。

target

用于 run() 方法调用的可调用对象。默认是 None,表示不需要调用任何方法。

name

 是线程名称。默认情况下,由 "Thread-N" 格式构成一个唯一的名称,其中 N 是小的十进制数。

args

 是用于调用目标函数的参数元组。默认是 ()。

kwargs

 是用于调用目标函数的关键字参数字典。默认是 {}。

强制结束线程

threading库里没有强制结束的方法,但通过我不懈努力,终于查到这个方法。添加方法来结束进程,另外用到的库有两个

原文链接:https://www.codeleading.com/article/57951130241/

import ctypes
import inspect
def __async_raise(thread_Id, exctype):
    # 在子线程内部抛出一个异常结束线程
    # 如果线程内执行的是unittest模块的测试用例, 由于unittest内部又异常捕获处理,所有这个结束线程
    # 只能结束当前正常执行的unittest的测试用例, unittest的下一个测试用例会继续执行,只有结束继续
    # 向unittest中添加测试用例才能使线程执行完任务,然后自动结束。
    thread_Id = ctypes.c_long(thread_Id)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_Id, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_Id, None)
        raise SystemError("PyThreadState_SEtAsyncExc failed")


def terminator(thread):  # 调用该方法传入需要结束的线程
    # 结束线程
    __async_raise(thread.ident, SystemExit)

  

posted @ 2021-12-03 15:00  哇!彦祖  阅读(67)  评论(1)    收藏  举报