python多线程【threading】模块

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值