强制终止线程

https://blog.csdn.net/A18373279153/article/details/80050177?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import threading
import time
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):
    _async_raise(thread.ident, SystemExit)


def test():
    while True:
        print('-------')
        # time.sleep(0.5)
        pass


if __name__ == "__main__":
    t = threading.Thread(target=test)
    t.start()
    time.sleep(5.2)
    print("main thread sleep finish")
    stop_thread(t)

获取返回值

https://blog.csdn.net/it_is_arlon/article/details/86594416

  • 实现逻辑:在 Thread object 中存储与取出值

    • 注意:这种方法不能在多进程,Process 中实现

      • 原因:主进程和子进程中的 Process oject 不是同一个
      • 而 Thread oject 在主线程和子线程中是同一个(id 相同)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import threading


class ResultThread(threading.Thread):
    def __init__(self, target=None, args=(), kwargs={}):
        super().__init__()
        self.target = target
        self.args = args
        self.kwargs = kwargs

    def run(self):
        self.result = self.target(*self.args, **self.kwargs)

    def get_result(self):
        try:
        return self.result
        except Exception:
        return None


def timeout_thread(timeout, target, *args, **kwargs):
    job = ResultThread(target=target, args=args, kwargs=kwargs)
    job.start()
    job.join(timeout)

    if job.is_alive():
        stop_thread(job)
    return job.get_result()

定时任务

使用 threading.Timer 类

  • Timer 类是 Thread 类的子类

    • Timer(delay, target, args, kwargs)