python的线程和c#的线程开启和使用方式不一样,下面说其中一种使用方式:
这是一个线程开始5秒后自动停止线程的示例
# -*- coding: utf-8 -*-
# @Author : 翻斗花园的突击手牛爷爷
# @Time : 2024/02/24 16:05
# @File : t_thread.py
# @Software : Pycharm
# @Desc : 多线程
import inspect
import threading
import ctypes
import time
def _async_raise(tid, exctype):
'''
停止线程, 对异常进行调整,并在需要时执行清理
:param tid: 线程id
:param exctype: 异常类型
:return: 无
'''
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:
# 如果它返回一个大于 1 的数字,则使用 exc=NULL 再次调用它以恢复效果
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
'''
停止线程
:param thread: 线程对象
:return: 无
'''
_async_raise(thread.ident, SystemExit)
# 定义一个方法作为线程的执行内容
def serial_read():
# 线程执行的代码
while True:
# 线程的具体操作
print("线程正在运行")
time.sleep(1)
# 创建线程对象,并指定要执行的方法
myThread = threading.Thread(target=serial_read)
# 启动线程
myThread.start()
# 停止线程
time.sleep(5)
stop_thread(myThread)