有时候有这样的需要,在某种情况下,需要在主线程中杀死之前创建的某个线程,可以使用下面的方法,通过调用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. 如何在VIM中保存编辑的只读文件

    我们经常碰到这样的情景:在VIM中编辑了一个系统配置文件,当需要保存时才发现当前的用户对该文件没有写入的权限, 这时候怎么办呢? 当需要保存时,输入以下的命令: :w !sudo tee %

  2. 不能聚焦元素问题 WebDriverException: Message: unknown error: cannot focus element

    上周碰到了 Unable to locate element,即“无法定位元素”,后靠两行代码解决: wait = ui.WebDriverWait(driver,5) wait.until(lamb ...

  3. apache配置文件详解(中英文对照版)

    # This is the main Apache server configuration file. It contains the # configuration directives that ...

  4. 自己整理的模拟爬虫的user-agent

    自己经常用的一些爬虫用的user-agent头部 This XML file does not appear to have any style information associated with ...

  5. ssd训练之bug:Invalid JPEG data or crop window, data size 565248

    bug信息 tensorflow.python.framework.errors_impl.InvalidArgumentError: Invalid JPEG data or crop window ...

  6. LeetCode 676. Implement Magic Dictionary实现一个魔法字典 (C++/Java)

    题目: Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll ...

  7. luoguP4254 [JSOI2008]Blue Mary开公司

    题意 李超树裸题,注意一开始截距是\(S-P\). code: #include<bits/stdc++.h> using namespace std; #define ls(p) (p& ...

  8. python科学计算库-pandas

    ------------恢复内容开始------------ 1.基本概念 在数据分析工作中,Pandas 的使用频率是很高的, 一方面是因为 Pandas 提供的基础数据结构 DataFrame 与 ...

  9. [随笔]ICPC2.0

    停更半年了.瞎扯下过去,现在与未来. 一.过去 1.插叙 讲道理我应该早就写这段在博客上了,不知怎么一直忘了. 在6月拿到ICPC南昌邀请赛的Ag还是比较满意,满意的最大原因是我弱校从没拿过Ag(? ...

  10. Windows环境Tomcat开启APR并配置http/2.0访问

    1.http/2.0需要开启https 参考:https://www.cnblogs.com/zhi-leaf/p/11978615.html 2.下载tcnative-1.dll文件 官网下载地址: ...