python创建线程和关闭线程

import threading
import inspect
import ctypes
import time

def task1():
  while True:
    print("hello")
    time.sleep(1)

def task2():
  while True:
    print("world")
    time.sleep(2)

def _async_raise(tid, exctype):
  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:
    ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
    raise SystemError("PyThreadState_SetAsyncExc failed")

def stop_thread(id):
  _async_raise(id, SystemExit)

if __name__ == '__main__':
  job1 = threading.Thread(task1)
  job2 = threading.Thread(task2)
  job1.start()
  job2.start()

  time.sleep(2)
  stop_thread(job1.ident)

  time.sleep(2)
  stop_thread(job2.ident)

 

 

posted @ 2023-03-23 17:54  琴声悠悠-悠悠琴声  阅读(145)  评论(0编辑  收藏  举报