有时候有这样的需要,在某种情况下,需要在主线程中杀死之前创建的某个线程,可以使用下面的方法,通过调用python内置API,在线程中抛出异常,使线程退出。

import threading
import time
import inspect
import ctypes def _async_raise(tid, exctype):
"""Raises an exception in the threads with id tid"""
if not inspect.isclass(exctype):
raise TypeError("Only types can be raised (not instances)")
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(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) class TestThread(threading.Thread):
def run(self):
print("begin run the child thread")
while True:
print("sleep 1s")
time.sleep(1) if __name__ == "__main__":
print("begin run main thread")
t = TestThread()
t.start()
time.sleep(3)
stop_thread(t)
print("main thread end")

这种方法是强制杀死线程,但是如果线程中涉及获取释放锁,可能会导致死锁。

更好的杀死线程的方式是使用退出标记,让线程自己退出,具体可以看我的下一篇博客 : https://www.cnblogs.com/lucky-heng/p/11991695.html

python中杀死线程的更多相关文章

  1. 理解 Python 中的线程

    原地址:http://blog.jobbole.com/52060/ 本文由 伯乐在线 - acmerfight 翻译自 Akshar Raaj.欢迎加入技术翻译小组.转载请参见文章末尾处的要求. 我 ...

  2. python中的线程技术

    #!/user/bin/env python # @Time :2018/7/7 11:42 # @Author :PGIDYSQ #@File :DaemonTest.py import threa ...

  3. Python中的线程和进程

    引入进程和线程的概念及区别 threading模块提供的类:   Thread, Lock, Rlock, Condition, [Bounded]Semaphore, Event, Timer, l ...

  4. Python之路-Python中的线程与进程

    一.发展背景 任务调度 大部分操作系统(如Windows.Linux)的任务调度是采用时间片轮转的抢占式调度方式,也就是说一个任务执行一小段时间后强制暂停去执行下一个任务,每个任务轮流执行.任务执行的 ...

  5. Python 中的线程-进程2

    原文:https://www.cnblogs.com/i-honey/p/7823587.html Python中实现多线程需要使用到 threading 库,其中每一个 Thread类 的实例控制一 ...

  6. 【Python】解析Python中的线程与进程

    基础知识 线程 进程 两者的区别 线程的类型 Python 多线程 GIL 创建多线程 线程合并 线程同步与互斥锁 可重入锁(递归锁) 守护线程 定时器 Python 多进程 创建多进程 多进程通信 ...

  7. python中的线程锁

    锁对象 原始锁是一个在锁定时不属于特定线程的同步基元组件.在Python中,它是能用的最低级的同步基元组件,由 _thread 扩展模块直接实现. 原始锁处于 "锁定" 或者 &q ...

  8. python主动杀死线程

    简介 在一些项目中,为了防止影响主进程都会在执行一些耗时动作时采取多线程的方式,但是在开启线程后往往我们会需要快速的停止某个线程的动作,因此就需要进行强杀线程,下面将介绍两种杀死线程的方式. 直接强杀 ...

  9. python中的线程

    1.线程的创建 1.1 通过thread类直接创建 import threading import time def foo(n): time.sleep(n) print("foo fun ...

随机推荐

  1. 3、mongoDB索引

    创建索引: db.imooc_collection.getIndexes() 查看索引情况 db.imooc_collection.ensureIndex({x:1}) 创建索引,x:1代表正向排序, ...

  2. 爬虫---PyQuert简介

    今天写一篇最近刚学习的一个第3方库pyquery,pyquery比bs4,lxml更强大的一个网页解析工具. 什么是pyQuery Pyquery是python的第3方库,PyQuery库也是一个非常 ...

  3. appium----Monkey测试

    做过app测试的应该都知道Monkey测试,今天简单的介绍下Monkey如何测试 什么是Monkey monkey测试的原理就是利用socket通讯的方式来模拟用户的按键输入,触摸屏输入,手势输入等, ...

  4. IDEA运行单个Java文件

    对于某些Java示例可能是只有单个文件,并不是完整的Java工程,那么要如何运行单个Java文件呢,以IDEA为例. 我的环境: IDEA 2017.3.2 jdk 1.8.0.73 操作步骤: 1. ...

  5. 爬虫 xpath 获取方式

    回顾 bs4 实例化bs对象,将页面源码数据加载到该对象中 定位标签:find('name',class_='xxx') findall() select() 将标签中的文本内容获取 string t ...

  6. Scrapy-splash

    Scrapy-splash Splash是一个javascript渲染服务.它是一个带有HTTP API的轻量级Web浏览器,使用Twisted和QT5在Python 3中实现.QT反应器用于使服务完 ...

  7. python copy和deepcopy

    Python FAQ2:赋值.浅拷贝.深拷贝的区别? 发表于 2014-08-15   |   分类于 Lang.-Python  |   在写Python过程中,经常会遇到对象的拷贝,如果不理解浅拷 ...

  8. mysql 日期处理函数

    首先创建一张实验用的一张表 drop table if exists t_student; create table t_student( id int primary key auto_increm ...

  9. verilog语法标准

    initial 中语句超过一需要添加begin和end: 1995 2001 介绍了当用逗号分隔敏感列表更方便构成事件控制表达式的选择条件: 2005 2001/2005语法标准,没有类型定义的任何标 ...

  10. rss订阅

    其实,本质上和爬虫没区别,只不过这是人家主动给你数据,而且是编排好格式后的数据 按个人主页url更新内容 去重,按照redis去重的方式 按时间保存内容 mysql 保存为时间格式(可以根据时间比较大 ...