python杀死一个线程的方法


Posted in Python onSeptember 06, 2015

最近在项目中遇到这一需求:

我需要一个函数工作,比如远程连接一个端口,远程读取文件等,但是我给的时间有限,比如,4秒钟如果你还没有读取完成或者连接成功,我就不等了,很可能对方已经宕机或者拒绝了。这样可以批量做一些事情而不需要一直等,浪费时间。

结合我的需求,我想到这种办法:

1、在主进程执行,调用一个进程执行函数,然后主进程sleep,等时间到了,就kill 执行函数的进程。

测试一个例子:

import time 
import threading 
def p(i): 
  print i 
class task(threading.Thread): 
  def __init__(self,fun,i): 
    threading.Thread.__init__(self) 
    self.fun = fun 
    self.i = i 
    self.thread_stop = False 
  def run(self): 
    while not self.thread_stop: 
      self.fun(self.i) 
  def stop(self): 
    self.thread_stop = True 
def test(): 
  thread1 = task(p,2) 
  thread1.start() 
  time.sleep(4) 
  thread1.stop() 
  return 
if __name__ == '__main__': 
  test()

经过测试只定了4秒钟。

经过我的一番折腾,想到了join函数,这个函数式用来等待一个线程结束的,如果这个函数没有结束的话,那么,就会阻塞当前运行的程序。关键是,这个参数有一个可选参数:join([timeout]):  阻塞当前上下文环境的线程,直到调用此方法的线程终止或到达指定的timeout(可选参数)。

不多说了贴下面代码大家看下:

#!/usr/bin/env python 
#-*-coding:utf-8-*- 
''''' 
author:cogbee 
time:2014-6-13 
function:readme 
''' 
import pdb 
import time 
import threading 
import os 
#pdb.set_trace() 
class task(threading.Thread): 
  def __init__(self,ip): 
    threading.Thread.__init__(self) 
    self.ip = ip 
    self.thread_stop = False 
  def run(self): 
    while not self.thread_stop:   
      #//添加你要做的事情,如果成功了就设置一下<span style="font-family: Arial, Helvetica, sans-serif;">self.thread_stop变量。</span> 
[python] view plaincopy在CODE上查看代码片派生到我的代码片
      if file != '': 
        self.thread_stop = True 
  def stop(self): 
    self.thread_stop = True 
def test(eachline): 
  global file 
  list = [] 
  for ip in eachline: 
    thread1 = task(ip) 
    thread1.start() 
    thread1.join(3) 
    if thread1.isAlive():   
      thread1.stop() 
      continue 
    #将可以读取的都存起来 
    if file != '': 
      list.append(ip) 
  print list 
if __name__ == '__main__': 
  eachline = ['1.1.1.1','222.73.5.54'] 
  test(eachline)

下面给大家分享我写的一段杀死线程的代码。

由于python线程没有提供abort方法,分享下面一段代码杀死线程:

import threading 
import inspect 
import ctypes 
def _async_raise(tid, exctype):
  """raises the exception, performs cleanup if needed"""
  if not inspect.isclass(exctype):
    raise TypeError("Only types can be raised (not instances)")
  res = ctypes.pythonapi.PyThreadState_SetAsyncExc(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, 0)
    raise SystemError("PyThreadState_SetAsyncExc failed")
class Thread(threading.Thread):
  def _get_my_tid(self):
    """determines this (self's) thread id"""
    if not self.isAlive():
      raise threading.ThreadError("the thread is not active")
    # do we have it cached?
    if hasattr(self, "_thread_id"):
      return self._thread_id
    # no, look for it in the _active dict
    for tid, tobj in threading._active.items():
      if tobj is self:
        self._thread_id = tid
        return tid
    raise AssertionError("could not determine the thread's id")
def raise_exc(self, exctype):
    """raises the given exception type in the context of this thread"""
    _async_raise(self._get_my_tid(), exctype)
def terminate(self):
    """raises SystemExit in the context of the given thread, which should 
    cause the thread to exit silently (unless caught)"""
    self.raise_exc(SystemExit)

使用例子:

>>> import time 
>>> from thread2 import Thread 
>>> 
>>> def f(): 
...   try: 
...     while True: 
...       time.sleep(0.1) 
...   finally: 
...     print "outta here" 
... 
>>> t = Thread(target = f) 
>>> t.start() 
>>> t.isAlive() 
True 
>>> t.terminate() 
>>> t.join() 
outta here 
>>> t.isAlive() 
False

试了一下,很不错,只是在要kill的线程中如果有time.sleep()时,好像工作不正常,没有找出真正的原因是什么。已经是很强大了。哈哈。

Python 相关文章推荐
使用Python中PDB模块中的命令来调试Python代码的教程
Mar 30 Python
python统计日志ip访问数的方法
Jul 06 Python
Python之自动获取公网IP的实例讲解
Oct 01 Python
用Python实现KNN分类算法
Dec 22 Python
Python线性回归实战分析
Feb 01 Python
python清除字符串中间空格的实例讲解
May 11 Python
Python数据预处理之数据规范化(归一化)示例
Jan 08 Python
Python字符串逆序输出的实例讲解
Feb 16 Python
如何使用Python进行OCR识别图片中的文字
Apr 01 Python
对Python3之方法的覆盖与super函数详解
Jun 26 Python
tensorflow将图片保存为tfrecord和tfrecord的读取方式
Feb 17 Python
15款Python编辑器的优缺点,别再问我“选什么编辑器”啦
Oct 19 Python
在Python的Flask框架中验证注册用户的Email的方法
Sep 02 #Python
Python实现身份证号码解析
Sep 01 #Python
实例Python处理XML文件的方法
Aug 31 #Python
通过实例浅析Python对比C语言的编程思想差异
Aug 30 #Python
使用Python脚本将文字转换为图片的实例分享
Aug 29 #Python
Python中常见的数据类型小结
Aug 29 #Python
深入解析Python中的lambda表达式的用法
Aug 28 #Python
You might like
Win2003+apache+PHP+SqlServer2008 配置生产环境
2014/07/29 PHP
对PHP新手的一些建议(PHP学习经验总结)
2014/08/20 PHP
PHP下的浮点运算不准的解决方法
2016/10/27 PHP
Mac系统完美安装PHP7详细教程
2017/06/06 PHP
PHP扩展mcrypt实现的AES加密功能示例
2019/01/29 PHP
javascript 主动派发事件总结
2011/08/09 Javascript
理解Angular数据双向绑定
2016/01/10 Javascript
JavaScript中原型链存在的问题解析
2016/09/25 Javascript
使用vue.js实现联动效果的示例代码
2017/01/10 Javascript
vue 计时器组件的实现代码
2017/09/14 Javascript
利用nodeJs anywhere搭建本地服务器环境的方法
2018/05/12 NodeJs
javascript使用正则表达式实现注册登入校验
2020/09/23 Javascript
小议Python中自定义函数的可变参数的使用及注意点
2016/06/21 Python
Django框架实现逆向解析url的方法
2018/07/04 Python
解决django后台样式丢失,css资源加载失败的问题
2019/06/11 Python
Python中一个for循环循环多个变量的示例
2019/07/16 Python
python利用datetime模块计算程序运行时间问题
2020/02/20 Python
Python 如何实现访问者模式
2020/07/28 Python
如何基于Python pygame实现动画跑马灯
2020/11/18 Python
解决import tensorflow导致jupyter内核死亡的问题
2021/02/06 Python
美国指甲油品牌:Deco Miami
2017/01/30 全球购物
英国豪华装饰照明品牌的在线零售商:Inspyer Lighting
2019/12/10 全球购物
美国体育用品商店:Academy Sports + Outdoors
2020/01/04 全球购物
Python如何实现单例模式
2016/06/03 面试题
J2EE模式面试题
2016/10/11 面试题
架构师岗位职责
2013/11/18 职场文书
自我鉴定书
2014/03/24 职场文书
活动总结格式范文
2014/04/26 职场文书
小学德育工作经验交流材料
2014/05/22 职场文书
销售员未完成销售业绩的检讨书
2014/10/12 职场文书
会计专业自荐信范文
2015/03/05 职场文书
开学第一周总结
2015/07/16 职场文书
教师理论学习心得体会
2016/01/21 职场文书
MySQL官方导出工具mysqlpump的使用
2021/05/21 MySQL
Mysql systemctl start mysqld报错的问题解决
2021/06/03 MySQL
室外天线与收音机天线杆接合方法
2022/04/05 无线电